﻿using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Linq.Extensions;
using Abp.UI;
using Camc.Quality.Authorization.Roles;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bop;
using Camc.Quality.Common;
using Camc.Quality.Common.CommonDate;
using Camc.Quality.DataDictionary;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.OperationHistory;
using Camc.Quality.ProductionPlan;
using Camc.Quality.Quality;
using Camc.Quality.RecordTable.FormClass;
using Camc.Quality.StoreManagement.StoragePut;
using Camc.Quality.SystemManagement;
using Camc.Quality.TrepanningManager.BomAnalyse;
using Camc.Quality.TrepanningManager.MatingManager;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static Camc.Quality.StoreManagement.StoragePut.StorePutContent;
using static Camc.Quality.StoreManagement.StoragePut.StoreStockContent;

namespace Camc.Quality.StoreManagement
{
    public class PartsDeliveryAppService : QualityAppServiceBase
    {
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        private readonly IRepository<TechniqueEntity, Guid> _techniqueEntityRepository;
        private readonly IRepository<ProcessesEntity, Guid> _processesEntityRepository;
        private readonly IRepository<WorkStepEntity, Guid> _workStepEntityRepository;
        public readonly IRepository<StoreStockContent, Guid> _storeStockContentRepsitory;
        private readonly IRepository<LoadPieceEntity, Guid> _loadPieceRepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentrepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNoderepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        public readonly IRepository<StoreStock, Guid> _storeStockRepsitory;
        public readonly IRepository<StorePutContent, Guid> _storePutContentRepsitory;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<DeliveryDocument, Guid> _deliveryDocumentRepository;
        private readonly IRepository<MakeTask, Guid> _makeTaskRepository;
        private readonly IRepository<DeliveryOutRecord, Guid> _deliveryOutRecordRepository;
        private readonly IRepository<CancellingStocksDocument, Guid> _cancellingStocksDocumentRepository;
        private readonly IRepository<CancellingRecord, Guid> _cancellingRecordRepository;
        private readonly IRepository<InventoryStore, Guid> _inventoryStoreRecordRepository;
        private readonly IRepository<InventoryDetails, Guid> _inventoryDetailsRepository;
        private readonly IRepository<StoreContent, Guid> _storeRepository;
        private readonly BomAnalyseAppService _bomAnalyseAppServiceRepository;
        private readonly MatingManagerAppService _matingManagerAppServiceRepository;
        public readonly CodeFormatDescAppService _codeFormatDescAppServiceRepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly IRepository<Role> _roleRepository;
        private readonly IRepository<UserRole, long> _userRoleRepository;

        public PartsDeliveryAppService(
            IRepository<BopNode, Guid> bopNodeRepository,
            IRepository<BopDesc, Guid> bopDescRepository,
            IRepository<TechniqueEntity, Guid> techniqueEntityRepository,
            IRepository<ProcessesEntity, Guid> processesEntityRepository,
            IRepository<WorkStepEntity, Guid> workStepEntityRepository,
            IRepository<LoadPieceEntity, Guid> loadPieceRepository,
            IRepository<MaterialsContent, Guid> materialsContentrepository,
            IRepository<MaterialsNode, Guid> materialsNoderepository,
            IRepository<Sys_Code, Guid> sysCodeRepository,
            IRepository<StoreStock, Guid> storeStockRepsitory,
            IRepository<StorePutContent, Guid> storePutContentRepsitory,
            IRepository<User, long> userRepository,
            IRepository<DeliveryDocument, Guid> deliveryDocumentRepository,
            IRepository<MakeTask, Guid> makeTaskRepository,
            IRepository<StoreStockContent, Guid> storeStockContentRepsitory,
            IRepository<DeliveryOutRecord, Guid> deliveryOutRecordRepository,
            IRepository<CancellingStocksDocument, Guid> cancellingStocksDocumentRepository,
            IRepository<CancellingRecord, Guid> cancellingRecordRepository,
            IRepository<InventoryStore, Guid> inventoryStoreRecordRepository,
            IRepository<InventoryDetails, Guid> inventoryDetailsRepository,
            IRepository<StoreContent, Guid> storeRepository,
            BomAnalyseAppService bomAnalyseAppServiceRepository,
            MatingManagerAppService matingManagerAppServiceRepository,
            CodeFormatDescAppService codeFormatDescAppServiceRepository,
            IOperationHistoryAppService iOperationHistoryAppService,
            IRepository<Role> roleRepository,
            IRepository<UserRole, long> userRoleRepository
            )
        {
            _bopNodeRepository = bopNodeRepository;
            _bopDescRepository = bopDescRepository;
            _techniqueEntityRepository = techniqueEntityRepository;
            _processesEntityRepository = processesEntityRepository;
            _workStepEntityRepository = workStepEntityRepository;
            _loadPieceRepository = loadPieceRepository;
            _materialsContentrepository = materialsContentrepository;
            _materialsNoderepository = materialsNoderepository;
            _sysCodeRepository = sysCodeRepository;
            _storeStockRepsitory = storeStockRepsitory;
            _storePutContentRepsitory = storePutContentRepsitory;
            _userRepository = userRepository;
            _deliveryDocumentRepository = deliveryDocumentRepository;
            _makeTaskRepository = makeTaskRepository;
            _storeStockContentRepsitory = storeStockContentRepsitory;
            _deliveryOutRecordRepository = deliveryOutRecordRepository;
            _cancellingStocksDocumentRepository = cancellingStocksDocumentRepository;
            _cancellingRecordRepository = cancellingRecordRepository;
            _inventoryStoreRecordRepository = inventoryStoreRecordRepository;
            _inventoryDetailsRepository = inventoryDetailsRepository;
            _storeRepository = storeRepository;
            _bomAnalyseAppServiceRepository = bomAnalyseAppServiceRepository;
            _matingManagerAppServiceRepository = matingManagerAppServiceRepository;
            _codeFormatDescAppServiceRepository = codeFormatDescAppServiceRepository;
            _iOperationHistoryAppService = iOperationHistoryAppService;
            _roleRepository = roleRepository;
            _userRoleRepository = userRoleRepository;
        }


        /// <summary>
        /// 根据条件查询出库单据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<DeliveryTemp> GetDeliverys(SelectDeliveryInput input)
        {
            try
            {
                //根据 出库单据 获取出库数据
                var tempQuery = from temp in _deliveryDocumentRepository.GetAll()
                                orderby temp.CreationTime descending
                                select new
                                {
                                    Id = temp.Id,
                                    DeliveryNo = temp.DeliveryNo,
                                    StroeName = temp.StroeName,
                                    StoreId = temp.StoreId,
                                    AssemblyTaskNumber = temp.AssemblyTaskNumber,
                                    ProductCode = temp.ProductCode,
                                    SendTime = temp.SendTime,
                                    RetrievalStateDesc = GetEnumDesc(temp.RetrievalState),
                                    Remark = temp.Remark,
                                    OutPeople = temp.OutPeople,
                                    StorePutTime = temp.StorePutTime,
                                    IdentifyingPeople = temp.IdentifyingPeople,
                                    IdentifyingTime = temp.IdentifyingTime,
                                    RetrievalState = temp.RetrievalState,
                                    Contents = (from p in _deliveryOutRecordRepository.GetAll()
                                                where p.DeliveryDocumentId == temp.Id
                                                select new
                                                {
                                                    ReleaseOrder = p.ReleaseOrder,
                                                    QualifiedNumber = p.QualifiedNumber,
                                                }).ToList(),
                                };
                if (tempQuery.Count() == 0)
                {
                    return new PagedResultDto<DeliveryTemp>(0, new List<DeliveryTemp>());
                }
                tempQuery = tempQuery.WhereIf(input.StoreId != null, d => d.StoreId == input.StoreId)
                    .WhereIf(!string.IsNullOrEmpty(input.DeliveryNo), d => d.DeliveryNo.Contains(input.DeliveryNo))
                    .WhereIf(!string.IsNullOrEmpty(input.AssemblyTaskNumber), d => d.AssemblyTaskNumber.Contains(input.AssemblyTaskNumber))
                    .WhereIf(!string.IsNullOrEmpty(input.ProductCode), d => d.ProductCode.Contains(input.ProductCode))
                    .WhereIf(input.RetrievalState != null, d => d.RetrievalState == input.RetrievalState)
                    .WhereIf(!string.IsNullOrEmpty(input.SendTime), d => d.SendTime.Contains(input.SendTime))
                    .WhereIf(!string.IsNullOrEmpty(input.QualifiedNumber), d => d.Contents.Select(f => f.QualifiedNumber).Contains(input.QualifiedNumber))
                    .WhereIf(!string.IsNullOrEmpty(input.ReleaseOrder), d => d.Contents.Select(f => f.ReleaseOrder).Contains(input.ReleaseOrder)).AsQueryable();
                List<DeliveryTemp> deliveries = new List<DeliveryTemp>();

                foreach (var item in tempQuery)
                {
                    DeliveryTemp delivery = new DeliveryTemp();
                    delivery.Id = item.Id;
                    delivery.DeliveryNo = item.DeliveryNo;
                    delivery.StroeName = item.StroeName;
                    delivery.AssemblyTaskNumber = item.AssemblyTaskNumber;
                    delivery.ProductCode = item.ProductCode;
                    delivery.SendTime = item.SendTime;
                    delivery.RetrievalStateDesc = item.RetrievalStateDesc;
                    delivery.Remark = item.Remark;
                    delivery.OutPeople = item.OutPeople;
                    delivery.StorePutTime = item.StorePutTime;
                    delivery.IdentifyingPeople = item.IdentifyingPeople;
                    delivery.IdentifyingTime = item.IdentifyingTime;
                    //整合出库单据  合格证号 和 旅行单号
                    if (item.Contents != null)
                    {
                        if (item.Contents.Count > 0)
                        {
                            var qualifiedNumberList = item.Contents.Select(d => d.QualifiedNumber);
                            if (qualifiedNumberList.Count() > 0)
                            {
                                delivery.QualifiedNumber = string.Join(",", qualifiedNumberList.Distinct());
                            }
                            var releaseOrderList = item.Contents.Select(d => d.ReleaseOrder);
                            if (releaseOrderList.Count() > 0)
                            {
                                delivery.ReleaseOrder = string.Join(",", releaseOrderList.Distinct());
                            }
                        }
                    }
                    deliveries.Add(delivery);
                }
                DeliveryOutput output = new DeliveryOutput();
                output.Deliveries = deliveries.Distinct().ToList();
                int count = output.Deliveries.Count();
                if (count > 0)
                {
                    output.Deliveries = output.Deliveries.AsQueryable().PageBy(input).ToList();

                }
                return new PagedResultDto<DeliveryTemp>(count, output.Deliveries);
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        
        }

        /// <summary>
        /// 获取退库单据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<LibraryRetrievalOutput> GetLibraryRetrievals(LibraryRetrievalInput input)
        {
            //先获取退库单据 然后 取得退库单据明细  然后 根据晒选条件筛选
            var tempQuery = from temp in _cancellingStocksDocumentRepository.GetAll()
                            orderby temp.CreationTime descending
                            select new
                            {
                                Id = temp.Id,
                                CancellingStocksNo = temp.CancellingStocksNo,
                                DeliveryNo = temp.DeliveryNo,
                                StroeName = temp.StroeName,
                                StoreId = temp.StoreId,
                                AssemblyTaskNumber = temp.AssemblyTaskNumber,
                                Model = temp.Model,
                                ModelId=temp.ModelId,
                                LotNo = temp.LotNo,
                                LotNoId=temp.LotNoId,
                                CancellingDesc = GetEnumDesc(temp.Cancelling),
                                CancellingReason = temp.CancellingReason,
                                CancellingUser = temp.CancellingUser,
                                CancellingTime = temp.CancellingTime,
                                Contents = (from p in _cancellingRecordRepository.GetAll()
                                            where p.CancellingStocksId == temp.Id
                                            select new
                                            {
                                                ReleaseOrder = p.ReleaseOrder,
                                                QualifiedNumber = p.QualifiedNumber,
                                            }).ToList(),
                            };
            tempQuery = tempQuery.WhereIf(input.StoreId != null, d => d.StoreId == input.StoreId)
                .WhereIf(!string.IsNullOrEmpty(input.CancellingStocksNo), d => d.CancellingStocksNo.Contains(input.CancellingStocksNo))
                .WhereIf(!string.IsNullOrEmpty(input.AssemblyTaskNumber), d => d.AssemblyTaskNumber.Contains(input.AssemblyTaskNumber))
                .WhereIf(input.ModelId!=null, d => d.ModelId == input.ModelId)
                .WhereIf(input.LotNoId != null, d => d.LotNoId == input.LotNoId).AsQueryable();
            List<LibraryRetrievalOutput> libraryRetrievals = new List<LibraryRetrievalOutput>();
            if (!string.IsNullOrEmpty(input.QualifiedNumber))
            {
                foreach (var item in tempQuery)
                {
                    if (item.Contents.Select(d => d.QualifiedNumber).Contains(input.QualifiedNumber)) //ReleaseOrder->QualifiedNumber
                    {
                        LibraryRetrievalOutput libraryRetrieval = new LibraryRetrievalOutput();
                        libraryRetrieval.Id = item.Id;
                        libraryRetrieval.CancellingStocksNo = item.CancellingStocksNo;
                        libraryRetrieval.StroeName = item.StroeName;
                        libraryRetrieval.DeliveryNo = item.DeliveryNo;
                        libraryRetrieval.AssemblyTaskNumber = item.AssemblyTaskNumber;
                        libraryRetrieval.Model = item.Model;
                        libraryRetrieval.LotNo = item.LotNo;
                        libraryRetrieval.CancellingDesc = item.CancellingDesc;
                        libraryRetrieval.CancellingReason = item.CancellingReason;
                        libraryRetrieval.CancellingUser = item.CancellingUser;
                        libraryRetrieval.CancellingTime = item.CancellingTime;
                        libraryRetrievals.Add(libraryRetrieval);
                    }
                }
            }
            if (!string.IsNullOrEmpty(input.ReleaseOrder))
            {
                foreach (var item in tempQuery)
                {
                    if (item.Contents.Select(d => d.ReleaseOrder).Contains(input.ReleaseOrder))
                    {
                        LibraryRetrievalOutput libraryRetrieval = new LibraryRetrievalOutput();
                        libraryRetrieval.Id = item.Id;
                        libraryRetrieval.CancellingStocksNo = item.CancellingStocksNo;
                        libraryRetrieval.StroeName = item.StroeName;
                        libraryRetrieval.DeliveryNo = item.DeliveryNo;
                        libraryRetrieval.AssemblyTaskNumber = item.AssemblyTaskNumber;
                        libraryRetrieval.Model = item.Model;
                        libraryRetrieval.LotNo = item.LotNo;
                        libraryRetrieval.CancellingDesc = item.CancellingDesc;
                        libraryRetrieval.CancellingReason = item.CancellingReason;
                        libraryRetrieval.CancellingUser = item.CancellingUser;
                        libraryRetrieval.CancellingTime = item.CancellingTime;
                        libraryRetrievals.Add(libraryRetrieval);
                    }
                }
            }
            if (string.IsNullOrEmpty(input.ReleaseOrder) && string.IsNullOrEmpty(input.QualifiedNumber))
            {
                foreach (var item in tempQuery)
                {
                    
                        LibraryRetrievalOutput libraryRetrieval = new LibraryRetrievalOutput();
                        libraryRetrieval.Id = item.Id;
                        libraryRetrieval.CancellingStocksNo = item.CancellingStocksNo;
                        libraryRetrieval.StroeName = item.StroeName;
                        libraryRetrieval.DeliveryNo = item.DeliveryNo;
                        libraryRetrieval.AssemblyTaskNumber = item.AssemblyTaskNumber;
                        libraryRetrieval.Model = item.Model;
                        libraryRetrieval.LotNo = item.LotNo;
                        libraryRetrieval.CancellingDesc = item.CancellingDesc;
                        libraryRetrieval.CancellingReason = item.CancellingReason;
                        libraryRetrieval.CancellingUser = item.CancellingUser;
                        libraryRetrieval.CancellingTime = item.CancellingTime;
                        libraryRetrievals.Add(libraryRetrieval);
                }
            }
            int count = libraryRetrievals.Count;
            libraryRetrievals = libraryRetrievals.Distinct().AsQueryable().PageBy(input).ToList(); //增加了去重
            return  new PagedResultDto<LibraryRetrievalOutput>(count, libraryRetrievals) ;
        }


        private class CertificateTemp
        {

            public Guid Id { get; set; }
            /// <summary>
            /// 产品编号(件号)
            /// </summary>
            public string ProductNumber { get; set; }
            public OutboundStates OutboundState { get; set; }
            /// <summary>
            /// 是否预配套
            /// </summary>
            public IsSuits IsPreSuit { get; set; }
            /// <summary>
            /// 是否配套
            /// </summary>
            public IsSuits IsSuit { get; set; }
        }

        /// <summary>
        /// 查看新增、报废、返修、驳回单据信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public AddCertificateOutput GetCertificateByBusiness(CertificateByBusinessInput input)
        {
            var delivery = _deliveryDocumentRepository.FirstOrDefault(d => d.Id == input.Id);
            if (delivery != null)
            {
                var certificaQuery = _storePutContentRepsitory.GetAll().WhereIf(!string.IsNullOrEmpty(delivery.ReleaseOrder), item => item.ReleaseOrder == delivery.ReleaseOrder)
                .WhereIf(!string.IsNullOrEmpty(delivery.QualifiedNumber), item => item.QualifiedNumber == delivery.QualifiedNumber).ToList();
                AddCertificateOutput certificate = new AddCertificateOutput();
                if (certificaQuery.Count >= 1)
                {
                    certificate.ReleaseOrder = delivery.ReleaseOrder;
                    certificate.QualifiedNumber = delivery.QualifiedNumber;
                    certificate.ProductDrawingNo = certificaQuery.First().ProductDrawingNo;
                    certificate.ProductName = certificaQuery.First().ProductName;
                    certificate.Batch = certificaQuery.First().Batch;
                    certificate.QualifiedTaskNumber = certificaQuery.First().QualifiedTaskNumber;
                    certificate.StageMark = certificaQuery.First().StageMark;
                    certificate.ProductCode = certificaQuery.First().ProductCode;
                    certificate.SendTime = certificaQuery.First().SendTime;
                    var material = _materialsContentrepository.Get(certificaQuery.First().MaterialsContentId);
                    certificate.MaterialsNodeDesc = _materialsNoderepository.Get(material.MaterialsNodeId).MaterialTypeName;
                    certificate.MaterialCategoryDesc = _materialsNoderepository.Get(material.MaterialCategoryId).MaterialTypeName;
                    certificate.Module = certificaQuery.First().Module;
                    certificate.ExpirationDate = certificaQuery.First().ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : certificaQuery.First().ExpirationDate;
                    certificate.Unit = certificaQuery.First().Unit;
                    certificate.BinLocation = certificaQuery.First().BinLocation;
                    certificate.Quantity = certificaQuery.First().Quantity;
                    certificate.ProductNumber = certificaQuery.First().ProductNumberShow;
                    certificate.SpecialRecords = certificaQuery.First().SpecialRecords;
                    List<CertificateTemp> storeStockContents = new List<CertificateTemp>();
                    var tempOut = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.Id).Select(d => d.StoreStockContentId).ToList();
                
                    //根据业务单据 获取 物料信息 如果是新增的话就是  无预配套跟 配套 其他的都是 根据id 就可以获取
                    if (input.Type == 0)
                    {
                        storeStockContents = (from cc in _storeStockContentRepsitory.GetAll()
                                              join mm in tempOut on cc.Id equals mm
                                              select new CertificateTemp
                                              {
                                                  Id = cc.Id,
                                                  ProductNumber = cc.ProductNumber,
                                                  OutboundState=cc.OutboundState,
                                                  IsSuit=cc.IsSuit,
                                                  IsPreSuit=cc.IsPreSuit,
                                              }).ToList();

                    } else if (input.Type == 1)
                    {


                        if (delivery.RetrievalState == OutboundRetrieval.新增)
                        {
                            storeStockContents = (from cc in _storeStockContentRepsitory.GetAll().Where(d => d.StorePutContentId == certificaQuery.First().Id).Where(d=>d.IsPreSuit==IsSuits.否&& d.IsSuit == IsSuits.否)
                                                  select new CertificateTemp
                                                  {
                                                      Id = cc.Id,
                                                      ProductNumber = cc.ProductNumber,
                                                      OutboundState = cc.OutboundState,
                                                      IsSuit = cc.IsSuit,
                                                      IsPreSuit = cc.IsPreSuit,
                                                  })
                                           .ToList();
                        }
                        else
                        {
                            storeStockContents = (from cc in _storeStockContentRepsitory.GetAll().Where(d => d.StorePutContentId == certificaQuery.First().Id)
                                                  select new CertificateTemp
                                                  {
                                                      Id = cc.Id,
                                                      ProductNumber = cc.ProductNumber,
                                                      OutboundState = cc.OutboundState,
                                                      IsSuit = cc.IsSuit,
                                                      IsPreSuit = cc.IsPreSuit,
                                                  })
                                             .ToList();

                        }
                       
                    }

                    List<CertificateContent> contents = new List<CertificateContent>();
                    for (int i = 0; i < storeStockContents.Count; i++)
                    {
                        CertificateContent content = new CertificateContent();

                        var tem = tempOut.FindIndex(d=>d== storeStockContents[i].Id);
                        if (tem!=-1)
                        {
                            content.IsCheck = true;
                        }
                        content.StockContentId = storeStockContents[i].Id;
                        content.ProductNumber = storeStockContents[i].ProductNumber;
                        if (storeStockContents[i].OutboundState == OutboundStates.出库)
                        {
                            content.OutboundStateDesc = "已出库";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.未领料)
                        {
                            content.OutboundStateDesc = "未领料";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.是)
                        {
                            content.OutboundStateDesc = "已配套";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.否 && storeStockContents[i].IsPreSuit == IsSuits.是)
                        {
                            content.OutboundStateDesc = "已预配套,未配套";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.否 && storeStockContents[i].IsPreSuit == IsSuits.否)
                        {
                            content.OutboundStateDesc = "库存";
                        }
                        contents.Add(content);
                    }
                    certificate.WhereAbouts = delivery.WhereAbouts; 
                    certificate.OutNum = delivery.OutNum;
                    certificate.Remark = delivery.Remark;
                    certificate.operationPersonId = delivery.operationPersonId;
                    certificate.operationPerson = delivery.operationPerson;
                    certificate.operationTime = delivery.operationTime;
                    certificate.ScrapReason = delivery.ScrapReason;
                    certificate.ScrapReasonId = delivery.ScrapReasonId;
                    certificate.CertificateContents = contents;
                }
                return certificate;
            }
            else
            {
                throw new UserFriendlyException("无法查找该单据信息!");
            }
        }
        /// <summary>
        /// 修改新增、报废、返修、驳回单据信息
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage AlterCertificateByBusiness(AlterCertificateInput input)
        {
            //先获取单据 然后修改 单据信息
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var delivery = _deliveryDocumentRepository.Get(input.Id);
                if (!string.IsNullOrEmpty(delivery.IdentifyingPeople))
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该单据已经确认！无法操作该单据信息！";
                    return resultMessage;
                }
                List<StoreStockContent> stockContents = new List<StoreStockContent>();
                List<StoreStockContent> alterList = new List<StoreStockContent>();
                var deliveryOutQuery = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.Id);
                var deliveryOutTemp = deliveryOutQuery.Select(d => d.StoreStockContentId);
                #region 判断修改是否合法
                //驳回
                if (input.Operation == 2)
                {
                    var certificaQuery = _storePutContentRepsitory.GetAll().WhereIf(!string.IsNullOrEmpty(input.ReleaseOrder), item => item.ReleaseOrder == input.ReleaseOrder)
                         .WhereIf(!string.IsNullOrEmpty(input.QualifiedNumber), item => item.QualifiedNumber == input.QualifiedNumber).ToList();
                    if (certificaQuery.Count > 0)
                    {
                        var storeGuidList = certificaQuery.Select(d => d.Id).ToList();
                        alterList = (from cc in _storeStockContentRepsitory.GetAll()
                                     join mm in storeGuidList on cc.Id equals mm
                                     select cc).ToList();
                    }
                }
                else
                {
                    alterList = (from cc in _storeStockContentRepsitory.GetAll()
                                 join mm in input.StoreList on cc.Id equals mm
                                 select cc).ToList();
                }
                foreach (var item in alterList)
                {
                    if (item.OutboundState == OutboundStates.出库)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "已出库,请先退库后在出库！";
                        return resultMessage;
                        //throw new UserFriendlyException(item.ProductNumber + "已出库,请先退库后在出库！");
                    }
                    if (item.OutboundState == OutboundStates.未领料 && !deliveryOutTemp.Contains(item.Id))
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = item.ProductNumber + "已在其他出库单据,处于待领料状态,请先撤销后在出库！";
                        return resultMessage;
                        //throw new UserFriendlyException(item.ProductNumber + "已在其他出库单据,处于待领料状态,请先撤销后在出库！");
                    }
                    if (item.IsSuit == IsSuits.是)
                    {
                        if (input.IsRelieve == false)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = item.ProductNumber + "已配套,请先解除配套后在出库！";
                            return resultMessage;
                            //throw new UserFriendlyException(item.ProductNumber + "已配套,请先解除配套后在出库！");
                        }
                    }
                    if (item.IsPreSuit == IsSuits.是)
                    {
                        if (input.IsRelieve == false)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = item.ProductNumber + "已预配套,请先解除预配套后在出库！";
                            return resultMessage;
                            //throw new UserFriendlyException(item.ProductNumber + "已预配套,请先解除预配套后在出库！");
                        }
                    }
                    stockContents.Add(item);
                }
                #endregion
                var tempQuery = from cc in _storeStockContentRepsitory.GetAll()
                                join mm in deliveryOutTemp on cc.Id equals mm
                                select cc;
                //.Where(d => deliveryOutTemp.Contains(d.Id));
                foreach (var item in tempQuery)
                {
                    item.RetrievalState = null;
                    item.OutboundState = OutboundStates.在库;
                    _storeStockContentRepsitory.Update(item);
                }
                foreach (var item in deliveryOutQuery)
                {
                    _deliveryOutRecordRepository.Delete(item);
                }
                if (stockContents.Count == 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "系统未查找到符合条件要修改的物料!";
                    return resultMessage;
                }
                var taskQuery = from tempTask in _makeTaskRepository.GetAll() select new { Model = tempTask.Model, LotNo = tempTask.LotNo, JobNumber = tempTask.JobNumber };
                var tempOwnStock = stockContents[0];
                delivery.StoreId = tempOwnStock.StoreId;
                delivery.StroeName = tempOwnStock.StroeName;
                var ownTask = taskQuery.Where(d => d.Model == tempOwnStock.ProductCode && d.LotNo == tempOwnStock.SendTime).FirstOrDefault();
                if (ownTask != null)
                {
                    delivery.AssemblyTaskNumber = ownTask.JobNumber;
                }
                else
                {
                    delivery.AssemblyTaskNumber = "";
                }
                delivery.ProductCode = tempOwnStock.ProductCode;
                delivery.SendTime = tempOwnStock.SendTime;
                string deliveryStr = "";
                switch (input.Operation)
                {
                    case 0:

                        delivery.RetrievalState = OutboundRetrieval.报废;
                        delivery.OutPeopleId = GetCurrentUser().Id;
                        delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                        delivery.OutNum = input.OutNum;
                        delivery.Remark = input.Reason;
                        delivery.operationPersonId = input.operationPersonId;
                        delivery.operationPerson = input.operationPerson;
                        delivery.operationTime = input.operationTime;
                        delivery.ScrapReason = input.ScrapReason;
                        delivery.ScrapReasonId = input.ScrapReasonId;
                        delivery.ReleaseOrder = input.ReleaseOrder;
                        delivery.QualifiedNumber = input.QualifiedNumber;
                        _deliveryDocumentRepository.Update(delivery);
                        foreach (var item in stockContents)
                        {
                            //if (item.IsPreSuit == IsSuits.是)
                            //{
                            //    item.IsPreSuit = IsSuits.否;
                            //    item.BomAnalysecontentId = null;
                            //}
                            //if (item.IsSuit == IsSuits.是)
                            //{
                            //    item.IsSuit = IsSuits.否;
                            //    item.BomSuitContentId = null;
                            //}
                            item.OutboundState = OutboundStates.未领料;
                            item.MaterialsProperty = MaterialsPropertys.报废品;
                            item.RetrievalState = OutboundRetrieval.报废;
                            _storeStockContentRepsitory.Update(item);
                            DeliveryOutRecord record = new DeliveryOutRecord();
                            record.DeliveryDocumentId = delivery.Id;
                            record.StoreStockContentId = item.Id;
                            record.ProductNumber = item.ProductNumber;
                            record.ReleaseOrder = item.ReleaseOrder;
                            record.QualifiedNumber = item.QualifiedNumber;
                            _deliveryOutRecordRepository.Insert(record);
                            deliveryStr = deliveryStr + item.ProductNumber + ",";
                        }
                        break;
                    case 1:
                        delivery.RetrievalState = OutboundRetrieval.返修;
                        delivery.OutPeopleId = GetCurrentUser().Id;
                        delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                        delivery.OutNum = input.OutNum;
                        delivery.Remark = input.Reason;
                        delivery.operationPersonId = input.operationPersonId;
                        delivery.operationPerson = input.operationPerson;
                        delivery.operationTime = input.operationTime;
                        delivery.QualifiedNumber = input.QualifiedNumber;
                        _deliveryDocumentRepository.Update(delivery);

                        foreach (var item in stockContents)
                        {
                            item.OutboundState = OutboundStates.未领料;
                            item.MaterialsProperty = MaterialsPropertys.返修品;
                            item.RetrievalState = OutboundRetrieval.返修;
                            _storeStockContentRepsitory.Update(item);
                            DeliveryOutRecord record = new DeliveryOutRecord();
                            record.DeliveryDocumentId = delivery.Id;
                            record.StoreStockContentId = item.Id;
                            record.ProductNumber = item.ProductNumber;
                            record.ReleaseOrder = item.ReleaseOrder;
                            record.QualifiedNumber = item.QualifiedNumber;
                            _deliveryOutRecordRepository.Insert(record);
                            deliveryStr = deliveryStr + item.ProductNumber + ",";
                        }
                        break;
                    case 2:
                        if (stockContents.Count() > 0)
                        {
                            delivery.RetrievalState = OutboundRetrieval.驳回;
                            delivery.OutPeopleId = GetCurrentUser().Id;
                            delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                            delivery.OutNum = stockContents.Count();
                            delivery.Remark = input.Reason;
                            delivery.operationPersonId = input.operationPersonId;
                            delivery.operationPerson = input.operationPerson;
                            delivery.operationTime = input.operationTime;
                            delivery.QualifiedNumber = input.QualifiedNumber;
                            _deliveryDocumentRepository.Update(delivery);
                            foreach (var item in stockContents)
                            {
                                item.OutboundState = OutboundStates.未领料;
                                item.RetrievalState = OutboundRetrieval.驳回;
                                _storeStockContentRepsitory.Update(item);
                                DeliveryOutRecord record = new DeliveryOutRecord();
                                record.DeliveryDocumentId = delivery.Id;
                                record.StoreStockContentId = item.Id;
                                record.ProductNumber = item.ProductNumber;
                                record.ReleaseOrder = item.ReleaseOrder;
                                record.QualifiedNumber = item.QualifiedNumber;
                                _deliveryOutRecordRepository.Insert(record);
                                deliveryStr = deliveryStr + item.ProductNumber + ",";
                            }
                        }
                        break;
                    case 3:
                        delivery.WhereAbouts = input.WhereAbouts;
                        delivery.AssemblyTaskNumber = input.WhereAbouts;
                        delivery.RetrievalState = OutboundRetrieval.新增;
                        delivery.OutPeopleId = GetCurrentUser().Id;
                        delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                        delivery.OutNum = input.OutNum;
                        delivery.Remark = input.Reason;
                        delivery.ReleaseOrder = input.ReleaseOrder;
                        delivery.QualifiedNumber = input.QualifiedNumber;
                        _deliveryDocumentRepository.Update(delivery);
                        foreach (var item in stockContents)
                        {
                            item.OutboundState = OutboundStates.未领料;
                            item.RetrievalState = OutboundRetrieval.新增;
                            _storeStockContentRepsitory.Update(item);
                            DeliveryOutRecord record = new DeliveryOutRecord();
                            record.DeliveryDocumentId = delivery.Id;
                            record.StoreStockContentId = item.Id;
                            record.ProductNumber = item.ProductNumber;
                            record.ReleaseOrder = item.ReleaseOrder;
                            record.QualifiedNumber = item.QualifiedNumber;
                            _deliveryOutRecordRepository.Insert(record);
                            deliveryStr = deliveryStr + item.ProductNumber + ",";
                        }
                        break;
                }
                _iOperationHistoryAppService.InsertOperationLogNew(delivery.Id, BusinessTypes.出库管理, OperationTypes.修改, "修改出库单据,修改后具体的物料编号为:" + deliveryStr);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        ///新增 跟其他 初始化展示表单信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public NewCertificateOutput GetCertificateByNum(AddStoreInput input)
        {
            var certificaQuery = _storePutContentRepsitory.GetAll().WhereIf(!string.IsNullOrEmpty(input.ReleaseOrder), item => item.ReleaseOrder == input.ReleaseOrder)
                 .WhereIf(!string.IsNullOrEmpty(input.QualifiedNumber), item => item.QualifiedNumber == input.QualifiedNumber).ToList();
            if (certificaQuery.Count == 1)
            {
                NewCertificateOutput certificate = new NewCertificateOutput();
                certificate.ProductDrawingNo = certificaQuery.First().ProductDrawingNo;
                certificate.ProductName = certificaQuery.First().ProductName;
                certificate.Batch = certificaQuery.First().Batch;
                certificate.QualifiedTaskNumber = certificaQuery.First().QualifiedTaskNumber;
                certificate.StageMark = certificaQuery.First().StageMark;
                certificate.ProductCode = certificaQuery.First().ProductCode;
                certificate.SendTime = certificaQuery.First().SendTime;
                var material = _materialsContentrepository.Get(certificaQuery.First().MaterialsContentId);
                certificate.MaterialsNodeDesc = _materialsNoderepository.Get(material.MaterialsNodeId).MaterialTypeName;
                certificate.MaterialCategoryDesc = _materialsNoderepository.Get(material.MaterialCategoryId).MaterialTypeName;
                certificate.Module = certificaQuery.First().Module;
                certificate.ExpirationDate = certificaQuery.First().ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : certificaQuery.First().ExpirationDate;
                certificate.Unit = certificaQuery.First().Unit;
                certificate.BinLocation = certificaQuery.First().BinLocation;
                certificate.Quantity = certificaQuery.First().Quantity;
                certificate.ProductNumber = certificaQuery.First().ProductNumberShow;
                certificate.SpecialRecords = certificaQuery.First().SpecialRecords;
                var storeStockContents = _storeStockContentRepsitory.GetAll().Where(d => d.StorePutContentId == certificaQuery.First().Id).ToList();
                if (input.Type == 0) // 新增只显示自由件
                {
                    storeStockContents = storeStockContents.Where(d => d.IsPreSuit == IsSuits.否 && d.IsSuit == IsSuits.否).ToList();
                }
                List<CertificateContent> contents = new List<CertificateContent>();
                for (int i = 0; i < storeStockContents.Count; i++)
                {
                    CertificateContent content = new CertificateContent();
                    content.StockContentId = storeStockContents[i].Id;
                    content.ProductNumber = storeStockContents[i].ProductNumber;
                    if (storeStockContents[i].OutboundState == OutboundStates.出库)
                    {
                        content.OutboundStateDesc = "已出库";
                    }
                    else if (storeStockContents[i].OutboundState == OutboundStates.未领料)
                    {
                        content.OutboundStateDesc = "未领料";
                    }
                    else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.是)
                    {
                        content.OutboundStateDesc = "已配套";
                    }
                    else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.否 && storeStockContents[i].IsPreSuit == IsSuits.是)
                    {
                        content.OutboundStateDesc = "已预配套,未配套";
                    }
                    else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.否 && storeStockContents[i].IsPreSuit == IsSuits.否)
                    {
                        content.OutboundStateDesc = "库存";
                    }
                    contents.Add(content);
                }
                certificate.CertificateContents = contents;
                return certificate;
            }
            else if (certificaQuery.Count > 1)
            {
                throw new UserFriendlyException("请选择合格证号!");
            }
            else
            {

                return new NewCertificateOutput();
            }
        }

        #region 配套

        /// <summary>
        /// 配套出库显示
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<OutBoundOutput> DisplayNodeDetails(PartsOutboundInput input)
        {
             //说白了 这个功能就是  先获取 树节点下面的 所有 装入件明细的物料 个数 然后 点击个数选取物料 展示
            if (input.NodeId != Guid.Empty)
            {
                int route = RouteType(input.NodeId);
                List<OutBoundOutput> outputs = new List<OutBoundOutput>();
                var loadQuery = from temp in _loadPieceRepository.GetAll()
                                select new
                                {
                                    Id = temp.Id,
                                    Number = temp.Number,
                                    WorkStepEntityId = temp.WorkStepEntityId,
                                    Sort= temp.Sort
                                };
                var stockContent = from temp in _storeStockContentRepsitory.GetAll().Where(d=>d.LoadDetailsId!=null)
                                   select new
                                   {
                                       LoadDetailsId = temp.LoadDetailsId,
                                       IsSuit = temp.IsSuit,
                                       MaterialsContentId = temp.MaterialsContentId,
                                       IsPreSuit = temp.IsPreSuit,
                                       OutboundState = temp.OutboundState
                                   };
                int Level = 0;
                 
                
                switch (route)
                {
                    case 1:
                    case 2:
                        var bopNodes = _bopNodeRepository.GetAll().Where(d => d.ParentId == input.NodeId).OrderBy(d => d.CreationTime).ToList();
                        if (bopNodes.Count() > 0)
                        {
                            var bopDesc = _bopDescRepository.Get(bopNodes.First().BopDescId);
                            foreach (var item in bopNodes)
                            {

                                int ProcessDosage = 0;
                                int SuiteStock = 0;
                                int OutboundedNum = 0;
                                int OutboundQuantity = 0;
                                int ShortageNum = 0;
                                int DeliveredNum = 0;
                                int PreSuiteStock = 0;//预配套数量
                                int canPreSuite = 0;//可用预配套;
                                string AssortState = "";
                                if (item.ParentCode == "root")
                                {
                                    var totalMaterial = _bomAnalyseAppServiceRepository.GetExternalCall(item.NodeName, item.NodeDrawingNo, bopDesc.ModelId, bopDesc.LotNoId);
                                    PreSuiteStock = totalMaterial.Sum(d => d.PreSuiteStockAll);
                                }
                                else
                                {
                                    var coreGrade = _bopNodeRepository.GetAll().Where(d => d.NodeCode == item.ParentCode.Substring(0, 3) && d.BopDescId == item.BopDescId).FirstOrDefault();
                                    if (coreGrade != null)
                                    {
                                        var totalMaterial = _bomAnalyseAppServiceRepository.GetExternalCall(coreGrade.NodeName, coreGrade.NodeDrawingNo, bopDesc.ModelId, bopDesc.LotNoId);
                                        PreSuiteStock = totalMaterial.Sum(d => d.PreSuiteStockAll);
                                        canPreSuite = totalMaterial.Sum(d => d.DifferenceCount);
                                    }
                                    else
                                    {
                                        throw new UserFriendlyException("未找到该节点对应的芯级!");
                                    }
                                
                                }
                                var techQuery = _bopNodeRepository.GetAll().Where(d => d.NodeCode.StartsWith(item.NodeCode) && d.BopDescId==item.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                                if (techQuery.Count > 0)
                                {
                                    var workIds = _workStepEntityRepository.GetAll().Where(d => techQuery.Contains(d.TechniqueEntityId)).Select(d => d.Id);
                                    var loadList = from cc in loadQuery
                                                   join mm in workIds on cc.WorkStepEntityId equals mm
                                                   select cc;

                                                  // .Where(d => workIds.Contains(d.WorkStepEntityId));
                                    ProcessDosage = loadList.Sum(d => d.Number); //工艺用量
                                    var loadIds = loadList.Select(d => d.Id);
                                    if (loadIds.Count() > 0)
                                    {
                                        SuiteStock = (from cc in stockContent
                                                      join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                      where cc.IsSuit == IsSuits.是
                                                      select cc).Count(); //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是);//配套数量
                                        OutboundedNum = (from cc in stockContent
                                                         join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                         where cc.IsSuit == IsSuits.是 && cc.OutboundState == OutboundStates.出库
                                                         select cc).Count();
                                        //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.出库);//已出库
                                        DeliveredNum = (from cc in stockContent
                                                        join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                        where cc.IsSuit == IsSuits.是 && cc.OutboundState == OutboundStates.未领料
                                                        select cc).Count();

                                        //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.未领料);//待领料
                                        OutboundQuantity = (from cc in stockContent
                                                            join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                            where cc.IsSuit == IsSuits.是 && cc.OutboundState == OutboundStates.在库
                                                            select cc).Count();

                                        //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.在库);//待出库
                                        int tempFree = (from cc in stockContent
                                                        join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                        where cc.IsPreSuit == IsSuits.否 && cc.IsSuit == IsSuits.否 && cc.OutboundState == OutboundStates.在库
                                                        select cc).Count();

                                    }
                                    //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsPreSuit == IsSuits.否 && d.IsSuit == IsSuits.否 && d.OutboundState == OutboundStates.在库);//自由件
                                    //= stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsPreSuit == IsSuits.是);//预配套数量
                                    if (item.ParentCode == "root")
                                    {
                                        canPreSuite = PreSuiteStock - SuiteStock;
                                    }
                                    ShortageNum = ProcessDosage - SuiteStock > canPreSuite ? ProcessDosage - SuiteStock : 0;//缺料数量
                                    AssortState = GetAssortStateDesc(ProcessDosage, SuiteStock, PreSuiteStock, canPreSuite);
                                }

                                OutBoundOutput output = new OutBoundOutput();
                                PartsOutboundOutput temp = new PartsOutboundOutput();
                                temp.ProductDrawingNo = item.NodeDrawingNo;
                                temp.ProductName = item.NodeName;
                                temp.ProcessDosage = ProcessDosage;
                                temp.SuiteStock = SuiteStock;
                                temp.OutboundedNum = OutboundedNum;
                                temp.OutboundQuantity = OutboundQuantity;
                                temp.ShortageNum = ShortageNum;
                                temp.AssortState = AssortState;
                                temp.DeliveredNum = DeliveredNum;
                                Level++;
                                temp.Level = Level.ToString();
                                output.data = temp;
                                outputs.Add(output);
                            }
                        }
                        break;
                    case 3:
                        int techPreSuiteStock = 0;
                        int techPreDifferenceCount = 0;
                        var bopNode = _bopNodeRepository.Get(input.NodeId);
                        var coreGradeNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == bopNode.ParentCode.Substring(0, 3) && d.BopDescId == bopNode.BopDescId).FirstOrDefault();
                        if (coreGradeNode != null)
                        {
                            var bopDesc = _bopDescRepository.Get(bopNode.BopDescId);
                            var totalMaterial = _bomAnalyseAppServiceRepository.GetExternalCall(coreGradeNode.NodeName, coreGradeNode.NodeDrawingNo, bopDesc.ModelId, bopDesc.LotNoId);
                            techPreSuiteStock = totalMaterial.Sum(d => d.PreSuiteStockAll);
                            techPreDifferenceCount = totalMaterial.Sum(d => d.DifferenceCount);
                        }
                        else
                        {
                            throw new UserFriendlyException("未找到该节点对应的芯级!");
                        }


                        var techId = bopNode.TechniqueEntityId;
                        var proTemp = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == techId).OrderBy(d => d.ProcessesSequence).ToList();
                        if (proTemp.Count > 0)
                        {
                            foreach (var item in proTemp)
                            {
                                int ProcessDosage = 0;
                                int SuiteStock = 0;
                                int OutboundedNum = 0;
                                int OutboundQuantity = 0;
                                int ShortageNum = 0;
                                int DeliveredNum = 0;
                                string AssortState = "";
                                var workIds = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == item.Id).Select(d => d.Id);
                                if (workIds.Count() > 0)
                                {
                                   // var loadList = loadQuery.Where(d => workIds.Contains(d.WorkStepEntityId));

                                    var loadList = from cc in loadQuery
                                                   join mm in workIds on cc.WorkStepEntityId equals mm
                                                   select cc;
                                
                                    ProcessDosage = loadList.Sum(d => d.Number); //工艺用量
                                    var loadIds = loadList.Select(d => d.Id);
                                    if (loadIds.Count() > 0)
                                    {
                                        SuiteStock = (from cc in stockContent
                                                      join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                      where cc.IsSuit == IsSuits.是
                                                      select cc).Count();
                                        //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是);//配套数量
                                        OutboundedNum = (from cc in stockContent
                                                         join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                         where cc.IsSuit == IsSuits.是 && cc.OutboundState == OutboundStates.出库
                                                         select cc).Count();

                                        //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.出库);//已出库
                                        OutboundQuantity = (from cc in stockContent
                                                            join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                            where cc.IsSuit == IsSuits.是 && cc.OutboundState == OutboundStates.在库
                                                            select cc).Count();

                                        // stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.在库);//待出库
                                        DeliveredNum = (from cc in stockContent
                                                        join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                        where cc.IsSuit == IsSuits.是 && cc.OutboundState == OutboundStates.未领料
                                                        select cc).Count();
                                        //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.未领料);//待领料
                                        int tempFree = (from cc in stockContent
                                                        join mm in loadIds on cc.LoadDetailsId.Value equals mm
                                                        where cc.IsPreSuit == IsSuits.否 && cc.IsSuit == IsSuits.否 && cc.OutboundState == OutboundStates.在库
                                                        select cc).Count();
                                    }
                                    //stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsPreSuit == IsSuits.否 && d.IsSuit == IsSuits.否 && d.OutboundState == OutboundStates.在库);//自由件
                                    //int PreSuiteStock = stockContent.Count(d => loadIds.Contains(d.LoadDetailsId.Value) && d.IsPreSuit == IsSuits.是);//预配套数量
                                    //var canPreSuite = PreSuiteStock - SuiteStock;
                                    //ShortageNum = ProcessDosage - SuiteStock > canPreSuite ? ProcessDosage - SuiteStock : 0;//缺料数量
                                    ShortageNum = ProcessDosage - SuiteStock > techPreDifferenceCount ? ProcessDosage - SuiteStock : 0;//缺料数量
                                    AssortState = GetAssortStateDesc(ProcessDosage, SuiteStock, techPreSuiteStock, techPreDifferenceCount);
                                }
                                OutBoundOutput output = new OutBoundOutput();
                                PartsOutboundOutput temp = new PartsOutboundOutput();
                                temp.ProductDrawingNo = "工序" + item.ProcessesSequence.ToString() + " ";
                                temp.ProcessDosage = ProcessDosage;
                                temp.ProductName = item.ProcessesName;
                                temp.SuiteStock = SuiteStock;
                                temp.OutboundedNum = OutboundedNum;
                                temp.OutboundQuantity = OutboundQuantity;
                                temp.ShortageNum = ShortageNum;
                                temp.AssortState = AssortState;
                                temp.DeliveredNum = DeliveredNum;
                                Level++;
                                temp.Level = Level.ToString();
                                output.data = temp;
                                outputs.Add(output);
                            }
                        }
                        break;
                    case 4:

                        var proceTemp = _processesEntityRepository.Get(input.NodeId);

                        var coreNodeInput = (from temp in _bopNodeRepository.GetAll().Where(d=>d.TechniqueEntityId== proceTemp.TechniqueEntityId)
                               select new
                               {
                                   ParentCode = temp.ParentCode.Substring(0, 3),
                                   BopDescId = temp.BopDescId
                               }).FirstOrDefault();
                        if (coreNodeInput != null)
                        {
                            var coreNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == coreNodeInput.ParentCode && d.BopDescId == coreNodeInput.BopDescId).FirstOrDefault();
                            if (coreNode != null)
                            {
                                var bopDesc = _bopDescRepository.Get(coreNode.BopDescId);
                                var tempMaterialStatistics = _bomAnalyseAppServiceRepository.GetExternalCall(coreNode.NodeName, coreNode.NodeDrawingNo, bopDesc.ModelId, bopDesc.LotNoId);
        
                                var workTemp = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == input.NodeId).OrderBy(d => d.WorkStepNumber).ToList();
                                if (workTemp.Count > 0)
                                {
                                    var workIdList = workTemp.Select(d => d.Id).ToList();

                                    var tempLoadQuery= from cc in loadQuery
                                                       orderby cc.Sort
                                                       join mm in workIdList on cc.WorkStepEntityId equals mm
                                                       select cc;

                                    var loadData = (from tempData in tempLoadQuery
                                                    select new
                                                    {
                                                        Id = tempData.Id,
                                                        Number = tempData.Number,
                                                        WorkStepEntityId = tempData.WorkStepEntityId,
                                                    }).ToList();
                                    if (loadData.Count > 0)
                                    {
                                        var querySuit = from tempLoad in loadData
                                                        join tempSuid in stockContent on tempLoad.Id equals tempSuid.LoadDetailsId
                                                        select new
                                                        {
                                                            LoadDetailsId = tempSuid.LoadDetailsId,
                                                            IsSuit = tempSuid.IsSuit,
                                                            MaterialsContentId = tempSuid.MaterialsContentId,
                                                            IsPreSuit = tempSuid.IsPreSuit,
                                                            OutboundState = tempSuid.OutboundState
                                                        };
                                        //var tempQuery = (from tempStockContentResult in ( from tempLoad in loadData
                                        //                join tempStockContent in stockContent on tempLoad.Id equals tempStockContent.LoadDetailsId
                                        //                group tempStockContent by new { tempStockContent.MaterialsContentId, tempStockContent.LoadDetailsId } into g
                                        //                select new
                                        //                {
                                        //                    LoadDetailsId = g.Key.LoadDetailsId,
                                        //                    MaterialsContentId=g.Key.MaterialsContentId
                                        //                })
                                        //               join f in loadData on tempStockContentResult.LoadDetailsId equals f.Id
                                        //               join tempMaterial in _materialsContentrepository.GetAll() on tempStockContentResult.MaterialsContentId equals tempMaterial.Id
                                        //               join tempNode in _materialsNoderepository.GetAll() on tempMaterial.MaterialsNodeId equals tempNode.Id
                                        //               join tempSysCode in _sysCodeRepository.GetAll() on tempMaterial.UnitId equals tempSysCode.Id
                                        //               select new PartsOutboundOutput
                                        //               {
                                        //                   Id= tempStockContentResult.MaterialsContentId,
                                        //                   LoadDetailsId = f.Id,
                                        //                   MaterialTypeName = tempNode.MaterialTypeName,//物料类别
                                        //                   ProductName = tempMaterial.MaterialName,// 物料名称
                                        //                   ProductDrawingNo = tempMaterial.MaterialNo,//物料代码
                                        //                   Module = tempMaterial.Model,//规格
                                        //                   Unit = tempSysCode.Description,//单位
                                        //                   ProcessDosage = f.Number,//工艺用量
                                        //                   OutboundedNum = querySuit.Count(d => d.LoadDetailsId == f.Id && d.MaterialsContentId== tempStockContentResult.MaterialsContentId && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.出库),//已出库
                                        //                   SuiteStock = querySuit.Count(d => d.LoadDetailsId == f.Id && d.MaterialsContentId == tempStockContentResult.MaterialsContentId && d.IsSuit == IsSuits.是),//配套数量
                                        //                   OutboundQuantity = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId && d.OutboundState == OutboundStates.在库),//待出库
                                        //                   DeliveredNum = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.未领料 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId),//待领料
                                        //                   AssortState = GetAssortStateDesc(f.Number, querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId), querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsPreSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId)),
                                        //                   ShortageNum = f.Number - querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId)  > (querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsPreSuit == IsSuits.是 && d.IsSuit == IsSuits.否 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId)) ? f.Number - querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId) : 0,
                                        //               });
                                        for (int i = 0; i < workIdList.Count; i++)
                                        {
                                            var work = workTemp.Where(d => d.Id == workIdList[i]).First();
                                            OutBoundOutput output = new OutBoundOutput();
                                            PartsOutboundOutput temp = new PartsOutboundOutput();
                                            temp.ProductDrawingNo = "工步" + proceTemp.ProcessesSequence.ToString() + "-" + work.WorkStepNumber.ToString();
                                            temp.ProductName = work.WorkStepNumber.ToString();
                                            temp.MaterialsLevel = "工步";
                                            temp.Level = (i + 1).ToString();
                                            temp.NodeLevel = 9;
                                            output.data = temp;
                                            //var query = loadData.Where(d => d.WorkStepEntityId == workIdList[i]).Select(d => d.Id).ToList();


                                            //if (query.Count > 0)
                                            //{
                                            //  var tempStore = tempQuery.Where(d => query.Contains(d.LoadDetailsId));
                                            var tempStore = (from tempStockContentResult in (from tempLoad in (from f in loadData
                                                                                                               where f.WorkStepEntityId == workIdList[i]
                                                                                                               select new { Id = f.Id })
                                                                                             join tempStockContent in stockContent on tempLoad.Id equals tempStockContent.LoadDetailsId
                                                                                             group tempStockContent by new { tempStockContent.MaterialsContentId, tempStockContent.LoadDetailsId } into g
                                                                                             select new
                                                                                             {
                                                                                                 LoadDetailsId = g.Key.LoadDetailsId,
                                                                                                 MaterialsContentId = g.Key.MaterialsContentId
                                                                                             })
                                                             join f in loadData on tempStockContentResult.LoadDetailsId equals f.Id
                                                             join tempMaterial in _materialsContentrepository.GetAll() on tempStockContentResult.MaterialsContentId equals tempMaterial.Id
                                                             join tempSta in  tempMaterialStatistics on tempStockContentResult.MaterialsContentId equals tempSta.MaterialsContentId
                                                             join tempNode in _materialsNoderepository.GetAll() on tempMaterial.MaterialsNodeId equals tempNode.Id
                                                             join tempSysCode in _sysCodeRepository.GetAll() on tempMaterial.UnitId equals tempSysCode.Id
                                                             select new PartsOutboundOutput
                                                             {
                                                                 Id = tempStockContentResult.MaterialsContentId,
                                                                 LoadDetailsId = f.Id,
                                                                 MaterialTypeName = tempNode.MaterialTypeName,//物料类别
                                                                 ProductName = tempMaterial.MaterialName,// 物料名称
                                                                 ProductDrawingNo = tempMaterial.MaterialNo,//物料代码
                                                                 Module = tempMaterial.Model,//规格
                                                                 Unit = tempSysCode.Description,//单位
                                                                 ProcessDosage = f.Number,//工艺用量
                                                                 OutboundedNum = querySuit.Count(d => d.LoadDetailsId == f.Id && d.MaterialsContentId == tempStockContentResult.MaterialsContentId && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.出库),//已出库
                                                                 SuiteStock = querySuit.Count(d => d.LoadDetailsId == f.Id && d.MaterialsContentId == tempStockContentResult.MaterialsContentId && d.IsSuit == IsSuits.是),//配套数量
                                                                 OutboundQuantity = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId && d.OutboundState == OutboundStates.在库),//待出库
                                                                 DeliveredNum = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.未领料 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId),//待领料
                                                                 AssortState = GetAssortStateDesc(f.Number, querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId), tempSta.PreSuiteStockAll, tempSta.DifferenceCount),
                                                                 ShortageNum = f.Number - querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId) > tempSta.DifferenceCount ? f.Number - querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId) : 0,
                                                             }).ToList();
                                            List<OutBoundOutput> outputChildrens = new List<OutBoundOutput>();
                                            for (int j = 0; j < tempStore.Count; j++)
                                            {
                                                tempStore[j].Level = temp.Level + "." + (j + 1).ToString();
                                                tempStore[j].NodeLevel = 10;
                                                OutBoundOutput outputChildren = new OutBoundOutput();
                                                outputChildren.data = tempStore[j];
                                                outputChildrens.Add(outputChildren);
                                            }
                                            output.children = outputChildrens;
                                            // }
                                            outputs.Add(output);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                throw new UserFriendlyException("未找到该节点对应的芯级!");
                            }

                        }

                      
                        break;
                    case 5:
                        var workStep = _workStepEntityRepository.FirstOrDefault(d => d.Id == input.NodeId);
                        var workStepInput = (from temp in _bopNodeRepository.GetAll().Where(d=>d.TechniqueEntityId== workStep.TechniqueEntityId)
                                             select new
                                             {
                                                 ParentCode = temp.ParentCode.Substring(0, 3),
                                                 BopDescId = temp.BopDescId
                                             }).FirstOrDefault();

                        if (workStep != null)
                        {
                            var coreNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == workStepInput.ParentCode && d.BopDescId == workStepInput.BopDescId).FirstOrDefault();
                            if (coreNode != null)
                            {
                                var bopDesc = _bopDescRepository.Get(coreNode.BopDescId);
                                var tempMaterialStatistics = _bomAnalyseAppServiceRepository.GetExternalCall(coreNode.NodeName, coreNode.NodeDrawingNo, bopDesc.ModelId, bopDesc.LotNoId);
                                var loadData =
                                      (from tempData in _loadPieceRepository.GetAll().Where(d => d.WorkStepEntityId == workStep.Id).OrderBy(d => d.Sort)
                                       select new
                                       {
                                           Id = tempData.Id,
                                           Number = tempData.Number,
                                           WorkStepEntityId = tempData.WorkStepEntityId,
                                       }).ToList();
                                if (loadData.Count > 0)
                                {
                                    var querySuit = from tempLoad in loadData
                                                    join tempSuid in stockContent on tempLoad.Id equals tempSuid.LoadDetailsId
                                                    select tempSuid;
                                    var tempQuery = from tempStockContentResult in (from tempLoad in loadData
                                                                                    join tempStockContent in _storeStockContentRepsitory.GetAll() on tempLoad.Id equals tempStockContent.LoadDetailsId
                                                                                    group tempStockContent by new { tempStockContent.MaterialsContentId, tempStockContent.LoadDetailsId } into g
                                                                                    select new
                                                                                    {
                                                                                        LoadDetailsId = g.Key.LoadDetailsId,
                                                                                        MaterialsContentId = g.Key.MaterialsContentId
                                                                                    })
                                                    join f in loadData on tempStockContentResult.LoadDetailsId equals f.Id
                                                    join tempMaterial in _materialsContentrepository.GetAll() on tempStockContentResult.MaterialsContentId equals tempMaterial.Id
                                                    join tempSta in tempMaterialStatistics on tempStockContentResult.MaterialsContentId equals tempSta.MaterialsContentId
                                                    join tempNode in _materialsNoderepository.GetAll() on tempMaterial.MaterialsNodeId equals tempNode.Id
                                                    join tempSysCode in _sysCodeRepository.GetAll() on tempMaterial.UnitId equals tempSysCode.Id
                                                    select new PartsOutboundOutput
                                                    {
                                                        Id = tempStockContentResult.MaterialsContentId,
                                                        LoadDetailsId = f.Id,
                                                        MaterialTypeName = tempNode.MaterialTypeName,//物料类别
                                                        ProductName = tempMaterial.MaterialName,// 物料名称
                                                        ProductDrawingNo = tempMaterial.MaterialNo,//物料代码
                                                        Module = tempMaterial.Model,//规格
                                                        Unit = tempSysCode.Description,//单位
                                                        ProcessDosage = f.Number,//工艺用量
                                                        OutboundedNum = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.出库 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId),//已出库
                                                        SuiteStock = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId),//配套数量
                                                        OutboundQuantity = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.在库 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId),//待出库
                                                        DeliveredNum = querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.未领料 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId),//待领料
                                                        AssortState = GetAssortStateDesc(f.Number, querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId), tempSta.PreSuiteStockAll, tempSta.DifferenceCount),
                                                        ShortageNum = f.Number - querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId) > tempSta.DifferenceCount ? f.Number - querySuit.Count(d => d.LoadDetailsId == f.Id && d.IsSuit == IsSuits.是 && d.MaterialsContentId == tempStockContentResult.MaterialsContentId) : 0,
                                                    };

                                    foreach (var item in tempQuery)
                                    {
                                        OutBoundOutput output = new OutBoundOutput();
                                        Level++;
                                        item.Level = Level.ToString();
                                        item.NodeLevel = 10;
                                        output.data = item;
                                        outputs.Add(output);
                                    }
                                    //PartsOutboundOutput temp = new PartsOutboundOutput();
                                    //temp.ProductDrawingNo = "工步" + process.ProcessesSequence.ToString() + "-" + workStep.WorkStepNumber.ToString();
                                    //temp.ProductName = workStep.WorkStepNumber.ToString();
                                    //temp.MaterialsLevel = "工步";
                                    //output.data = temp;
                                    //output.children = tempQuery.ToList();
                                }
                            }
                                // var process = _processesEntityRepository.Get(workStep.ProcessesEntityId);
                          
                        }
                        break;
                    default:
                        break;
                }
                return outputs;
            }
            else
            {
                throw new Exception("传入数据有误!");
            }
        }
        /// <summary>
        /// 扫描标签获取信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public LabelInformation GetMaterialByLabel(PartsOutboundInput input)
        {
            int route = RouteType(input.NodeId);
            LabelInformation label = new LabelInformation();
            if (route == 4)
            {
                var processes = _processesEntityRepository.Get(input.NodeId);
                label.ProcessesName = processes.ProcessesName;
                var tech = _techniqueEntityRepository.Get(processes.TechniqueEntityId);
                label.TechniqueName = tech.TechniqueName;
                label.TechniqueNumber = tech.TechniqueNumber;
                var bopNode = _bopNodeRepository.FirstOrDefault(d => d.TechniqueEntityId == tech.Id);
                var bopNodeQuery = _bopNodeRepository.GetAll().Where(d => d.BopDescId == bopNode.BopDescId);
                if (bopNode.NodeLevel == 3)
                {
                    var parentNode = bopNodeQuery.FirstOrDefault(d => d.Id == bopNode.ParentId);
                    label.PartSleeve = parentNode.NodeName;
                    var coreNode = bopNodeQuery.FirstOrDefault(d => d.Id == parentNode.ParentId);
                    label.CoreGrade = coreNode.NodeName;
                }
                if (bopNode.NodeLevel == 2)
                {
                    label.PartSleeve = bopNode.NodeName;
                    var coreNode = bopNodeQuery.FirstOrDefault(d => d.Id == bopNode.ParentId);
                    label.CoreGrade = coreNode.NodeName;
                }
                var bopDesc = _bopDescRepository.Get(bopNode.BopDescId);
                label.Model = bopDesc.Model;
                label.LotNo = bopDesc.LotNo;
                label.BoundOutputs = DisplayNodeDetails(input);
            }
            if (route == 5)
            {
                var work = _workStepEntityRepository.Get(input.NodeId);
                var processes = _processesEntityRepository.Get(work.ProcessesEntityId);
                label.WorkStepName = "工步" + processes.ProcessesSequence.ToString() + "-" + work.WorkStepNumber.ToString();
                label.ProcessesName = processes.ProcessesName;
                var tech = _techniqueEntityRepository.Get(processes.TechniqueEntityId);
                label.TechniqueName = tech.TechniqueName;
                label.TechniqueNumber = tech.TechniqueNumber;
                var bopNode = _bopNodeRepository.FirstOrDefault(d => d.TechniqueEntityId == tech.Id);
                var bopNodeQuery = _bopNodeRepository.GetAll().Where(d => d.BopDescId == bopNode.BopDescId);
                if (bopNode.NodeLevel == 3)
                {
                    var parentNode = bopNodeQuery.FirstOrDefault(d => d.Id == bopNode.ParentId);
                    label.PartSleeve = parentNode.NodeName;
                    var coreNode = bopNodeQuery.FirstOrDefault(d => d.Id == parentNode.ParentId);
                    label.CoreGrade = coreNode.NodeName;
                }
                if (bopNode.NodeLevel == 2)
                {
                    label.PartSleeve = bopNode.NodeName;
                    var coreNode = bopNodeQuery.FirstOrDefault(d => d.Id == bopNode.ParentId);
                    label.CoreGrade = coreNode.NodeName;
                }
                var bopDesc = _bopDescRepository.Get(bopNode.BopDescId);
                label.Model = bopDesc.Model;
                label.LotNo = bopDesc.LotNo;
                label.BoundOutputs = DisplayNodeDetails(input);
            }
            return label;
        }

        /// <summary>
        ///配套出库
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage MatchingStore(MatchingStoreInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                DeliveryDocument delivery = new DeliveryDocument();
                var deliveryNo = _codeFormatDescAppServiceRepository.GetCodeFormat("出库管理");
                if (deliveryNo == null)
                {
                    delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                }
                else
                {
                    delivery.DeliveryNo = deliveryNo;
                }
                //delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1); 
                delivery.NodeId = input.NodeId;
                List<Guid> StoreIds = new List<Guid>();
                Dictionary<Guid, Guid> dic = new Dictionary<Guid, Guid>();
                var taskQuery = from tempTask in _makeTaskRepository.GetAll() select new { Model = tempTask.Model, LotNo = tempTask.LotNo, JobNumber = tempTask.JobNumber };
                // 前台传入 装入件 id 跟物料 集合 然后 保存入库单据就可
                foreach (var item in input.Matchings)
                {
                    if (item.StoreIdList != null)
                    {
                        if (item.StoreIdList.Count > 0)
                        {
                            StoreIds.AddRange(item.StoreIdList);
                            foreach (var tempItem in item.StoreIdList)
                            {
                                dic[tempItem] = item.LoadDetailsId;
                            }
                        }
                        else
                        {
                            var tempStockIds = _storeStockContentRepsitory.GetAll().Where(d => d.LoadDetailsId == item.LoadDetailsId && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.在库);
                            foreach (var tempItem in tempStockIds)
                            {
                                dic[tempItem.Id] = tempItem.LoadDetailsId.Value;
                            }
                            if (tempStockIds.Count() > 0)
                            {
                                StoreIds.AddRange(tempStockIds.Select(d => d.Id));
                            }
                        }
                    }
                    else
                    {
                        var tempStockIds = _storeStockContentRepsitory.GetAll().Where(d => d.LoadDetailsId == item.LoadDetailsId && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.在库);
                        foreach (var tempItem in tempStockIds)
                        {
                            dic[tempItem.Id] = tempItem.LoadDetailsId.Value;
                        }
                        if (tempStockIds.Count() > 0)
                        {
                            StoreIds.AddRange(tempStockIds.Select(d => d.Id));
                        }
                    }
                }
                if (StoreIds.Count > 0)
                {
                    var tempOwnStock = _storeStockContentRepsitory.Get(StoreIds[0]);
                    var workId = _loadPieceRepository.Get(tempOwnStock.LoadDetailsId.Value).WorkStepEntityId;
                    var techId = _workStepEntityRepository.Get(workId).TechniqueEntityId;
                    var bopDescId = _bopNodeRepository.FirstOrDefault(d => d.TechniqueEntityId == techId).BopDescId;
                    if (bopDescId != null)
                    {
                        var tempBopDesc = _bopDescRepository.Get(bopDescId);
                        delivery.ProductCode = tempBopDesc.Model;
                        delivery.SendTime = tempBopDesc.LotNo;
                        var ownTask = taskQuery.Where(d => d.Model == tempBopDesc.Model && d.LotNo == tempBopDesc.LotNo).FirstOrDefault();
                        if (ownTask != null)
                        {
                            delivery.AssemblyTaskNumber = ownTask.JobNumber;
                        }
                        else
                        {
                            delivery.AssemblyTaskNumber = "";
                        }
                    }
                    delivery.StoreId = tempOwnStock.StoreId;
                    delivery.StroeName = tempOwnStock.StroeName;
                    delivery.RetrievalState = OutboundRetrieval.配套;
                    delivery.OutPeopleId = GetCurrentUser().Id;
                    delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                    delivery.OutNum = StoreIds.Count;
                    delivery.StorePutTime = DateTime.Now;
                    delivery.WorkStepIdList = string.Join(",", input.Matchings.Select(d => d.LoadDetailsId));
                    var guid = _deliveryDocumentRepository.InsertAndGetId(delivery);
                    string productNumberStr = "";
                    foreach (var item in StoreIds)
                    {
                        var ownStock = _storeStockContentRepsitory.Get(item);
                        ownStock.OutboundState = OutboundStates.未领料;
                        ownStock.RetrievalState = OutboundRetrieval.配套;
                        _storeStockContentRepsitory.Update(ownStock);
                        DeliveryOutRecord record = new DeliveryOutRecord();
                        record.DeliveryDocumentId = guid;
                        record.StoreStockContentId = item;
                        record.ProductNumber = ownStock.ProductNumber;
                        record.ReleaseOrder = ownStock.ReleaseOrder;
                        record.LoadDetailsId = dic[item];
                        record.QualifiedNumber = ownStock.QualifiedNumber;
                        _deliveryOutRecordRepository.Insert(record);
                        productNumberStr = productNumberStr + ownStock.ProductNumber + ",";
                    }
                    _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.出库管理, OperationTypes.配套出库, "配套出库:" + productNumberStr + "等物料信息。");
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "请选择符合条件的配套物料！";
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        /// <summary>
        /// 配套修改查看
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public LabelInformation ModifMatchingOutput(Guid Id)
        {
            var delivery = _deliveryDocumentRepository.Get(Id);
            if (delivery.NodeId != null)
            {
                PartsOutboundInput input = new PartsOutboundInput();
                input.NodeId = delivery.NodeId.Value;
                LabelInformation label = GetMaterialByLabel(input);
                var tempOut = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == Id).Select(d => d.StoreStockContentId);
               // var tempStoreStockContent = _storeStockContentRepsitory.GetAll().Where(d => tempOut.Contains(Id)).Select(d => d.LoadDetailsId);
                var tempStoreStockContent = (from te in _storeStockContentRepsitory.GetAll()
                                             join mm in tempOut on te.Id equals mm
                                             select te.LoadDetailsId
                                            ).ToList();

                if (tempStoreStockContent.Count() > 0)
                {
                    List<OutBoundOutput> checkOutputs = new List<OutBoundOutput>();
                    for (int i = 0; i < label.BoundOutputs.Count; i++)
                    {
                        if (label.BoundOutputs[i].children.Count > 0)
                        {
                            for (int j = 0; j < label.BoundOutputs[i].children.Count; j++)
                            {

                                var tem = tempStoreStockContent.FindIndex(d => d == label.BoundOutputs[i].children[j].data.LoadDetailsId);
                                if (tem != -1)
                                {
                                    checkOutputs.Add(label.BoundOutputs[i].children[j]);
                                }
                                //if (tempStoreStockContent.Contains(label.BoundOutputs[i].children[j].data.LoadDetailsId))
                                //{
                                //    checkOutputs.Add(label.BoundOutputs[i].children[j]);
                                //}
                            }
                        }
                        else
                        {
                            var tem = tempStoreStockContent.FindIndex(d => d == label.BoundOutputs[i].data.LoadDetailsId);
                            if (tem != -1)
                            {
                                checkOutputs.Add(label.BoundOutputs[i]);
                            }
                            //if (tempStoreStockContent.Contains(label.BoundOutputs[i].data.LoadDetailsId))
                            //{
                            //    checkOutputs.Add(label.BoundOutputs[i]);
                            //}
                        }
                    }
                    label.CheckOutputs = checkOutputs;
                }
                return label;
            }
            else
            {
                throw new UserFriendlyException("系统查找信息有误!请刷新后重新获取！");
            }
        }
        /// <summary>
        /// 配套单据查看
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public LabelInformation LookforMatchingOutput(Guid Id)
        {
            var delivery = _deliveryDocumentRepository.Get(Id);
            if (delivery.NodeId != null)
            {
                PartsOutboundInput input = new PartsOutboundInput();
                input.NodeId = delivery.NodeId.Value;

                DateTime beforDT = System.DateTime.Now;

                //耗时巨大的代码  
                LabelInformation label = GetMaterialByLabel(input);
                DateTime afterDT = System.DateTime.Now;
                TimeSpan ts = afterDT.Subtract(beforDT);
                Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds);
                 
                var tempOut = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == Id).Select(d => d.StoreStockContentId);
                var tempStoreStockContent = (from te in _storeStockContentRepsitory.GetAll()
                                            join mm in tempOut on te.Id equals mm
                                            select te.LoadDetailsId
                                            ).ToList();
                // 展示物料的时候 展示节点所有的物料 然后 有 选中的物料就 check状态 筛选出来 就可以 前台 根据这个打勾
                if (tempStoreStockContent.Count() > 0)
                {
                    List<OutBoundOutput> checkOutputs = new List<OutBoundOutput>();
                    for (int i = 0; i < label.BoundOutputs.Count; i++)
                    {
                        if (label.BoundOutputs[i].children.Count > 0)
                        {
                            int sumCurrentDelivery = 0;
                            for (int j = 0; j < label.BoundOutputs[i].children.Count; j++)
                            {
                                var tem = tempStoreStockContent.FindIndex(d => d == label.BoundOutputs[i].children[j].data.LoadDetailsId);
                                if (tem != -1)
                                {
                                    checkOutputs.Add(label.BoundOutputs[i].children[j]);
                                    int count = tempStoreStockContent.Count(d => d == label.BoundOutputs[i].children[j].data.LoadDetailsId);
                                    label.BoundOutputs[i].children[j].data.CurrentDelivery = count;
                                    sumCurrentDelivery = sumCurrentDelivery + count;
                                }
                                //if (tempStoreStockContent.Contains(label.BoundOutputs[i].children[j].data.LoadDetailsId))
                                //{
                                //    checkOutputs.Add(label.BoundOutputs[i].children[j]);
                                //}
                            }
                            label.BoundOutputs[i].data.CurrentDelivery = sumCurrentDelivery;
                        }
                        else
                        {
                            var tem = tempStoreStockContent.FindIndex(d => d == label.BoundOutputs[i].data.LoadDetailsId);
                            if (tem != -1)
                            {
                                checkOutputs.Add(label.BoundOutputs[i]);
                                label.BoundOutputs[i].data.CurrentDelivery= tempStoreStockContent.Count(d => d == label.BoundOutputs[i].data.LoadDetailsId);
                            }
                            //if (tempStoreStockContent.Contains(label.BoundOutputs[i].data.LoadDetailsId))
                            //{
                            //    checkOutputs.Add(label.BoundOutputs[i]);
                            //}
                        }
                    }
                    label.CheckOutputs = checkOutputs;
                }


                return label;
            }
            else
            {
                throw new UserFriendlyException("系统查找信息有误!请刷新后重新获取！");
            }
        }
        /// <summary>
        /// 配套退库记录查看
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public LabelInformation StockReturnRecordMatchingOutput(Guid Id)
        {
            var cancelling = _cancellingStocksDocumentRepository.Get(Id);
            var delivery = _deliveryDocumentRepository.Get(cancelling.DeliveryDocumentId);
            if (delivery.NodeId != null)
            {
                PartsOutboundInput input = new PartsOutboundInput();
                input.NodeId = delivery.NodeId.Value;
                LabelInformation label = GetMaterialByLabel(input);
                var tempOut = _cancellingRecordRepository.GetAll().Where(d => d.CancellingStocksId == Id).Select(d => d.StoreStockContentId);
                var tempStoreStockContent = (from te in _storeStockContentRepsitory.GetAll()
                                             join mm in tempOut on te.Id equals mm
                                             select te.LoadDetailsId
                                            ).ToList();

                if (tempStoreStockContent.Count() > 0)
                {
                     List<OutBoundOutput> checkOutputs = new List<OutBoundOutput>();
                    for (int i = 0; i < label.BoundOutputs.Count; i++)
                    {
                        if (label.BoundOutputs[i].children.Count > 0)
                        {
                            int sumCurrentDelivery = 0;
                            for (int j = 0; j < label.BoundOutputs[i].children.Count; j++)
                            {
                                var tem = tempStoreStockContent.FindIndex(d => d == label.BoundOutputs[i].children[j].data.LoadDetailsId);
                                if (tem != -1)
                                {
                                    checkOutputs.Add(label.BoundOutputs[i].children[j]);

                                    int count = tempStoreStockContent.Count(d => d == label.BoundOutputs[i].children[j].data.LoadDetailsId);
                                    label.BoundOutputs[i].children[j].data.CurrentDelivery = count;
                                    sumCurrentDelivery = sumCurrentDelivery + count;
                                }
                                // if (tempStoreStockContent.Contains(label.BoundOutputs[i].children[j].data.LoadDetailsId))
                                //{
                                //    checkOutputs.Add(label.BoundOutputs[i].children[j]);
                                //}
                            }
                            label.BoundOutputs[i].data.CurrentDelivery = sumCurrentDelivery;
                        }
                        else
                        {
                            var tem = tempStoreStockContent.FindIndex(d => d == label.BoundOutputs[i].data.LoadDetailsId);
                            if (tem != -1)
                            {
                                checkOutputs.Add(label.BoundOutputs[i]);
                                label.BoundOutputs[i].data.CurrentDelivery = tempStoreStockContent.Count(d => d == label.BoundOutputs[i].data.LoadDetailsId);
                            }
                            //if (tempStoreStockContent.Contains(label.BoundOutputs[i].data.LoadDetailsId))
                            //{
                            //    checkOutputs.Add(label.BoundOutputs[i]);
                            //}
                        }
                    }
                    label.CheckOutputs = checkOutputs;

                }
                var tempCancel = _cancellingStocksDocumentRepository.Get(Id);
                label.CancellingReason = tempCancel.CancellingReason;
                label.CancellingTime = tempCancel.CancellingTime;
                label.CancellingUser = tempCancel.CancellingUser;

                label.CancellingUserId = tempCancel.CancellingUserId;
                return label;
            }
            else
            {
                throw new UserFriendlyException("系统查找信息有误!请刷新后重新获取！");
            }
        }

        #region 修改配套出库
        public void UpdateMatching(MatchingUpdateInput input)
        {
            var temoDelivery = _deliveryDocumentRepository.FirstOrDefault(d => d.Id == input.Id);
            var tempOut = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.Id);
            var GuidList = tempOut.Select(d => d.StoreStockContentId);
            foreach (var item in tempOut)
            {
                _deliveryOutRecordRepository.Delete(item);
            }
            //根据 单据 筛选以前 的物料和 新料 老的物料没有勾选的 就更新 新的 物料选中的 就新增
            if (temoDelivery != null)
            {
                List<Guid> StoreIds = new List<Guid>();
                Dictionary<Guid, Guid> dic = new Dictionary<Guid, Guid>();
                foreach (var item in input.OldMatchings)
                {
                    if (item.StoreIdList != null)
                    {
                        if (item.StoreIdList.Count > 0)
                        {
                            StoreIds.AddRange(item.StoreIdList);
                            foreach (var tempItem in item.StoreIdList)
                            {
                                dic[tempItem] = item.LoadDetailsId;
                            }
                        }
                        else
                        {
                            var tempStockIds = _storeStockContentRepsitory.GetAll().Where(d => d.LoadDetailsId == item.LoadDetailsId && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.在库);
                            foreach (var tempItem in tempStockIds)
                            {
                                dic[tempItem.Id] = tempItem.LoadDetailsId.Value;
                            }
                            if (tempStockIds.Count() > 0)
                            {
                                StoreIds.AddRange(tempStockIds.Select(d => d.Id));
                            }
                        }
                    }
                    else
                    {
                        var tempStockIds = _storeStockContentRepsitory.GetAll().Where(d => d.LoadDetailsId == item.LoadDetailsId && d.IsSuit == IsSuits.是 && d.OutboundState == OutboundStates.在库);
                        foreach (var tempItem in tempStockIds)
                        {
                            dic[tempItem.Id] = tempItem.LoadDetailsId.Value;
                        }
                        if (tempStockIds.Count() > 0)
                        {
                            StoreIds.AddRange(tempStockIds.Select(d => d.Id));
                        }
                    }
                }
                var tempQuery = _storeStockContentRepsitory.GetAll().Where(d => GuidList.Contains(d.Id));
                foreach (var item in tempQuery)
                {
                    item.OutboundState = OutboundStates.在库;
                    item.RetrievalState = null;
                    _storeStockContentRepsitory.Update(item);
                }
                string deliveryStr = "";
                foreach (var item in StoreIds)
                {
                    var ownStock = _storeStockContentRepsitory.Get(item);
                    ownStock.OutboundState = OutboundStates.未领料;
                    ownStock.RetrievalState = OutboundRetrieval.配套;
                    _storeStockContentRepsitory.Update(ownStock);
                    DeliveryOutRecord record = new DeliveryOutRecord();
                    record.DeliveryDocumentId = input.Id;
                    record.StoreStockContentId = item;
                    record.ProductNumber = ownStock.ProductNumber;
                    record.ReleaseOrder = ownStock.ReleaseOrder;
                    record.LoadDetailsId = dic[item];
                    record.QualifiedNumber = ownStock.QualifiedNumber;
                    _deliveryOutRecordRepository.Insert(record);
                    deliveryStr = deliveryStr + ownStock.ProductNumber + ",";
                }
                _iOperationHistoryAppService.InsertOperationLogNew(input.Id, BusinessTypes.出库管理, OperationTypes.修改, "修改出库单据,修改后具体的物料编号为:" + deliveryStr);
            }
        }
        #endregion

        /// <summary>
        /// 根据Id查询库存信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public MaterialDetailsOutput GetMaterialDetails(MaterialDetailInput input)
        {
            var users = (from tempUser in _userRepository.GetAll() select new { Id = tempUser.Id, UserName = tempUser.Surname + tempUser.Name }).ToList();

            var tempQuery = (from tempStoreContent in _storeStockContentRepsitory.GetAll().Where(d => d.LoadDetailsId == input.LoadDetailsId &&d.MaterialsContentId==input.MaterialsContentId && d.IsSuit == IsSuits.是)
                            join tempStorePut in _storePutContentRepsitory.GetAll() on tempStoreContent.StorePutContentId equals tempStorePut.Id
                            join tempMaterial in _materialsContentrepository.GetAll() on tempStoreContent.MaterialsContentId equals tempMaterial.Id
                            join tempNode in _materialsNoderepository.GetAll() on tempMaterial.MaterialsNodeId equals tempNode.Id
                            join tempMaterialCategory in _materialsNoderepository.GetAll() on tempMaterial.MaterialCategoryId equals tempMaterialCategory.Id
                            join ownUser in users on tempStorePut.StorePutPeopleId equals ownUser.Id
                            join tempIdentifyingPeople in users on tempStorePut.IdentifyingPeopleId equals tempIdentifyingPeople.Id
                            orderby tempStoreContent.CreationTime, tempStoreContent.QualifiedNumber, tempStoreContent.ReleaseOrder
                             select new MaterialDetails
                            {
                                Id = tempStoreContent.Id,
                                StroeName = tempStoreContent.StroeName,
                                ProductDrawingNo = tempStoreContent.ProductDrawingNo,
                                ProductName= tempStoreContent.ProductName,
                                Module = tempStoreContent.Module,
                                MaterialTypeName = tempNode.MaterialTypeName,
                                MaterialCategoryName = tempMaterialCategory.MaterialTypeName,
                                OutboundStatesDesc = tempStoreContent.OutboundState == OutboundStates.在库 ? "在库" : tempStoreContent.OutboundState == OutboundStates.出库 ? "已出库" : "未领料",
                                QualifiedNumber = tempStoreContent.QualifiedNumber,
                                ReleaseOrder = tempStoreContent.ReleaseOrder,
                                QCCardNo = tempStorePut.QCCardNo,
                                ProductCode = tempStorePut.ProductCode,
                                SendTime = tempStorePut.SendTime,
                                Batch = tempStorePut.Batch,
                                Quantity = tempStorePut.Quantity,
                                ProductNumber = tempStoreContent.ProductNumber,
                                QualifiedTaskNumber = tempStorePut.QualifiedTaskNumber,
                                AssemblyTaskNumber = tempStorePut.AssemblyTaskNumber,
                                ExpirationDate = tempStorePut.ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : tempStorePut.ExpirationDate,
                                StorePutPeopleDesc = ownUser.UserName,
                                StorePutTime = tempStorePut.StorePutTime,
                                Remark = tempStorePut.Remark,
                                IdentifyingPeople = tempIdentifyingPeople.UserName,
                                IdentifyingTime = tempStorePut.IdentifyingTime,
                            }).ToList();
            MaterialDetailsOutput output = new MaterialDetailsOutput();
            switch (input.operation)
            {
                case 0:
                    output.MaterialDetails = tempQuery.ToList();
                    break;
                case 1:
                    //排除已有单据的表单
                    if (tempQuery != null)
                    {
                        //var formDeliveryGuid = tempQuery.Select(d => d.Id);
                        //var tempOut = (from cc in _deliveryOutRecordRepository.GetAll()
                        //               join mm in formDeliveryGuid on cc.StoreStockContentId equals mm
                        //               select cc).ToList();
                        //var cancel = _cancellingRecordRepository.GetAll().Select(d => d.StoreStockContentId).Distinct();

                            /* _deliveryOutRecordRepository.GetAll().Where(d => formDeliveryGuid.Contains(d.StoreStockContentId)).ToList();*/
                        if (tempQuery.Count > 0)
                        {
                            //var deliveryOutGuids = tempOut.Select(d => d.DeliveryDocumentId).Distinct().ToList();
                            //var deliveryOutTemp = _deliveryOutRecordRepository.GetAll().Where(d => deliveryOutGuids.Contains(d.DeliveryDocumentId)).Select(d => d.StoreStockContentId).ToList();
                            //if (cancel.Count() > 0)
                            //{
                            //    var insectCancel = deliveryOutTemp.Intersect(deliveryOutTemp).ToList();
                            //    for (int i = 0; i < insectCancel.Count; i++)
                            //    {
                            //        deliveryOutTemp.Remove(insectCancel[i]);

                            //    }
                            //}
                            foreach (var item in tempQuery)
                            {
                                //var tem = deliveryOutTemp.FindIndex(d => d == item.Id);
                                if (item.OutboundStatesDesc != "在库")
                                {
                                    item.LoadCheck = false;
                                }
                                else
                                {
                                    item.LoadCheck = true;
                                }
                                //if (deliveryOutTemp.Contains(item.Id))
                                //{
                                //    item.LoadCheck = false;
                                //}
                                //else
                                //{
                                //    item.LoadCheck = true;
                                //}
                            }
                        }
                        //else
                        //{
                        //    foreach (var item in tempQuery)
                        //    {

                        //         item.LoadCheck = true;
                        //    }

                        //}
                        output.MaterialDetails = tempQuery.ToList();
                    }
                    break;
                case 2:
                    if (tempQuery != null)
                    {
                        var tempOut = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.Id).Select(d => d.StoreStockContentId).ToList();
                        output.MaterialDetails = (from cc in tempQuery
                                                  join mm in tempOut on cc.Id equals mm
                                                  select cc).ToList();
                            //tempQuery.Where(d => tempOut.Contains(d.Id)).ToList();
                        if (output.MaterialDetails.Count == 0)
                        {
                            throw new UserFriendlyException("该表单无此次选择仓库信息！请尝试查看其他物料！");
                        }
                    }
                    break;
                case 3:
                    //屏蔽其他单据 保留自身单据
                    if (tempQuery != null)
                    {
                        var formHasgGuids = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.Id).Select(d => d.StoreStockContentId).ToList();
                        //var formDeliveryGuid = tempQuery.Select(d => d.Id);
                        //var tempOut = (from cc in _deliveryOutRecordRepository.GetAll()
                        //               join mm in formDeliveryGuid on cc.StoreStockContentId equals mm
                        //               select cc).ToList();
                        //_deliveryOutRecordRepository.GetAll().Where(d => formDeliveryGuid.Contains(d.StoreStockContentId)).ToList();
                        tempQuery = tempQuery.Where(d => d.OutboundStatesDesc == "在库"|| formHasgGuids.Contains(d.Id)).ToList();
                        if (tempQuery.Count > 0)
                        {
                            //var deliveryOutGuids = tempOut.Select(d => d.DeliveryDocumentId).Distinct().ToList();
                            //var deliveryOutTemp = _deliveryOutRecordRepository.GetAll().Where(d => deliveryOutGuids.Contains(d.DeliveryDocumentId)).Select(d => d.StoreStockContentId).Where(d => !formHasgGuids.Contains(d)).ToList();
                            //tempQuery = tempQuery.Where(d => !deliveryOutTemp.Contains(d.Id)).ToList();
                            foreach (var item in tempQuery)
                            {
                                var tem = formHasgGuids.FindIndex(d => d == item.Id);
                                if (tem != -1)
                                {
                                    item.CanBeChoose = true;
                                }
                                else
                                {
                                    item.CanBeChoose = false;
                                }
                                //if (formHasgGuids.Contains(item.Id))
                                //{
                                //    item.CanBeChoose = true;
                                //}
                                //else
                                //{
                                //    item.CanBeChoose = false;
                                //}
                            }
                            output.MaterialDetails = tempQuery.ToList();
                        }
                        //else
                        //{
                        //    foreach (var item in tempQuery)
                        //    {
                        //        var tem = formHasgGuids.FindIndex(d => d == item.Id);
                        //        if (tem != -1)
                        //        {
                        //            item.CanBeChoose = true;
                        //        }
                        //        else
                        //        {
                        //            item.CanBeChoose = false;
                        //        }
                        //    }

                           
                        //    output.MaterialDetails = tempQuery.ToList();

                        //}
                    }
                    break;
                case 4:
                    //查看已执行退库操作的物料
                    if (tempQuery != null)
                    {
                        var tempDelivery = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.Id && d.IsCancelling == true).Select(d => d.StoreStockContentId);
                        if (tempDelivery.Count() > 0)
                        {
                            output.MaterialDetails = (from cc in tempQuery
                                                      join mm in tempDelivery on cc.Id equals mm
                                                      select cc).ToList();
                                //tempQuery.Where(d => tempDelivery.Contains(d.Id)).ToList();
                        }
                        else
                        {
                            throw new UserFriendlyException("没有符合条件的物料");
                        }
                    }
                    break;
                case 5:
                    //本次单据供选择退库操作的物料
                    if (tempQuery != null)
                    {
                        var tempDelivery = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.Id && d.IsCancelling == false).Select(d => d.StoreStockContentId);
                        if (tempDelivery.Count() > 0)
                        {
                            output.MaterialDetails = (from cc in tempQuery
                                                      join mm in tempDelivery on cc.Id equals mm
                                                      select cc).ToList();
                                                         //tempQuery.Where(d => tempDelivery.Contains(d.Id)).ToList();
                        }
                        else
                        {
                            throw new UserFriendlyException("没有符合条件的物料");
                        }
                    }
                    break;
                case 6:
                    ///退库记录查看
                    if (tempQuery != null)
                    {
                        var query = _cancellingRecordRepository.GetAll().Where(d => d.CancellingStocksId == input.Id).Select(d => d.StoreStockContentId).ToList();
                        if (query.Count > 0)
                        {
                            output.MaterialDetails = (from cc in tempQuery
                                                      join mm in query on cc.Id equals mm
                                                      select cc).ToList();
                            //tempQuery.Where(d => query.Contains(d.Id)).ToList();
                        }
                    }
                    break;
            }
            return output;
        }
        #endregion

        #region 新增出库
        /// <summary>
        /// 获取放行单号
        /// </summary>
        /// <returns></returns>
        public List<string> GetReleaseOrders()
        {
            var tempContents = _storeStockContentRepsitory.GetAll().Where(d=>d.ReleaseOrder!=null).Select(d => d.ReleaseOrder);

            if (tempContents.Count() > 0)
            {
                return tempContents.Distinct().ToList();
            }
            else
            {
                return new List<string>();
            }
        }
        /// <summary>
        /// 获取合格证号
        /// </summary>
        /// <returns></returns>
        public List<string> GetQualifiedNumber(string ReleaseOrders)
        {
            var tempContents = _storeStockContentRepsitory.GetAll().WhereIf(!string.IsNullOrEmpty(ReleaseOrders), item => item.ReleaseOrder == ReleaseOrders).Where(d => d.QualifiedNumber != null).Select(d => d.QualifiedNumber);

            if (tempContents.Count() > 0)
            {
                return tempContents.Distinct().ToList();
            }
            else
            {
                return new List<string>();
            }
        }
        /// <summary>
        /// 新增出库
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage AddStoreOut(AddCertificateInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            if (input.StoreList.Count == 0)
            {
                resultMessage.code = 1;
                resultMessage.Message = "请选择出库物料！";
                return resultMessage;
            }
            try
            {
                List<StoreStockContent> stockContents = new List<StoreStockContent>();
                foreach (var item in input.StoreList)
                {
                    var ownContent = _storeStockContentRepsitory.Get(item);
                    if (ownContent.OutboundState == OutboundStates.出库)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "已出库,请先退库后在出库！";
                        return resultMessage;
                    }
                    if (ownContent.OutboundState == OutboundStates.未领料)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "正在出库待领料,请先撤销后在出库！";
                        return resultMessage;
                    }
                    if (ownContent.IsSuit == IsSuits.是)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "已配套,请先解除配套后在出库！";
                        return resultMessage;
                    }
                    if (ownContent.IsPreSuit == IsSuits.是)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "已预配套,请先解除预配套后在出库！";
                        return resultMessage;
                    }
                    stockContents.Add(ownContent);
                }
                //var taskQuery = from tempTask in _makeTaskRepository.GetAll() select new { Model = tempTask.Model, LotNo = tempTask.LotNo, JobNumber = tempTask.JobNumber };
                DeliveryDocument delivery = new DeliveryDocument();
                var deliveryNo = _codeFormatDescAppServiceRepository.GetCodeFormat("出库管理");
                if (deliveryNo == null)
                {
                    delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                }
                else
                {
                    delivery.DeliveryNo = deliveryNo;
                }
                //delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                var tempOwnStock = stockContents[0];
                delivery.StoreId = tempOwnStock.StoreId;
                delivery.StroeName = tempOwnStock.StroeName;
                delivery.AssemblyTaskNumber = input.WhereAbouts;
                //if (!string.IsNullOrEmpty(input.WhereAbouts))
                //{
                   
                    //var ownTask = taskQuery.Where(d => d.JobNumber == input.WhereAbouts).FirstOrDefault();
                    //if (ownTask != null)
                    //{
                    //    delivery.AssemblyTaskNumber = ownTask.JobNumber;
                    //}
                    //else
                    //{
                    //    delivery.AssemblyTaskNumber = "";
                    //}
                //}
                delivery.WhereAbouts = input.WhereAbouts;
                delivery.RetrievalState = OutboundRetrieval.新增;
                delivery.OutPeopleId = GetCurrentUser().Id;
                delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                delivery.OutNum = input.OutNum;
                delivery.Remark = input.Reason;
                delivery.ReleaseOrder = input.ReleaseOrder;
                delivery.QualifiedNumber = input.QualifiedNumber;
                delivery.StorePutTime = DateTime.Now;
                var guid = Guid.NewGuid();
                delivery.Id = guid;
                _deliveryDocumentRepository.Insert(delivery);
                string deliveryStr = "";
                foreach (var item in stockContents)
                {
                    item.OutboundState = OutboundStates.未领料;
                    item.RetrievalState = OutboundRetrieval.新增;
                    _storeStockContentRepsitory.Update(item);
                    DeliveryOutRecord record = new DeliveryOutRecord();
                    record.DeliveryDocumentId = guid;
                    record.StoreStockContentId = item.Id;
                    record.ProductNumber = item.ProductNumber;
                    record.ReleaseOrder = item.ReleaseOrder;
                    record.QualifiedNumber = item.QualifiedNumber;
                    _deliveryOutRecordRepository.Insert(record);
                    deliveryStr = deliveryStr + record.ProductNumber + ",";
                }
                _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.出库管理, OperationTypes.新增出库, "新增出库:" + deliveryStr + "等物料信息。");
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        /// <summary>
        /// 获取退库新增单据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public AddCertificateOutput GetCancelRecord(Guid Id)
        {
            var cancelling = _cancellingStocksDocumentRepository.FirstOrDefault(d => d.Id == Id);
            if (cancelling != null)
            {
                var delivery = _deliveryDocumentRepository.Get(cancelling.DeliveryDocumentId);
                var certificaQuery = _storePutContentRepsitory.GetAll().WhereIf(!string.IsNullOrEmpty(delivery.ReleaseOrder), item => item.ReleaseOrder == delivery.ReleaseOrder)
                .WhereIf(!string.IsNullOrEmpty(delivery.QualifiedNumber), item => item.QualifiedNumber == delivery.QualifiedNumber).ToList();
                AddCertificateOutput certificate = new AddCertificateOutput();
                if (certificaQuery.Count == 1)
                {
                    certificate.ReleaseOrder = delivery.ReleaseOrder;
                    certificate.QualifiedNumber = delivery.QualifiedNumber;
                    certificate.ProductDrawingNo = certificaQuery.First().ProductDrawingNo;
                    certificate.ProductName = certificaQuery.First().ProductName;
                    certificate.Batch = certificaQuery.First().Batch;
                    certificate.QualifiedTaskNumber = certificaQuery.First().QualifiedTaskNumber;
                    certificate.StageMark = certificaQuery.First().StageMark;
                    certificate.ProductCode ="";
                    certificate.SendTime = "";
                    var material = _materialsContentrepository.Get(certificaQuery.First().MaterialsContentId);
                    certificate.MaterialsNodeDesc = _materialsNoderepository.Get(material.MaterialsNodeId).MaterialTypeName;
                    certificate.MaterialCategoryDesc = _materialsNoderepository.Get(material.MaterialCategoryId).MaterialTypeName;
                    certificate.Module = certificaQuery.First().Module;
                    certificate.ExpirationDate = certificaQuery.First().ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : certificaQuery.First().ExpirationDate;
                    certificate.Unit = certificaQuery.First().Unit;
                    certificate.BinLocation = certificaQuery.First().BinLocation;
                    certificate.Quantity = certificaQuery.First().Quantity;
                    certificate.ProductNumber = certificaQuery.First().ProductNumberShow;
                    certificate.SpecialRecords = certificaQuery.First().SpecialRecords;
                    List<StoreStockContent> storeStockContents = new List<StoreStockContent>();
                    var tempOut = _cancellingRecordRepository.GetAll().Where(d => d.CancellingStocksId == Id).Select(d => d.StoreStockContentId);
                    storeStockContents = (from cc in _storeStockContentRepsitory.GetAll()
                                          join mm in tempOut on cc.Id equals mm select cc).ToList();
                                         //.Where(d => tempOut.Contains(d.Id)).ToList();
                    List<CertificateContent> contents = new List<CertificateContent>();
                    for (int i = 0; i < storeStockContents.Count; i++)
                    {
                        CertificateContent content = new CertificateContent();
                        content.StockContentId = storeStockContents[i].Id;
                        content.ProductNumber = storeStockContents[i].ProductNumber;
                        if (storeStockContents[i].OutboundState == OutboundStates.出库)
                        {
                            content.OutboundStateDesc = "已出库";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.未领料)
                        {
                            content.OutboundStateDesc = "未领料";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.是)
                        {
                            content.OutboundStateDesc = "已配套";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.否 && storeStockContents[i].IsPreSuit == IsSuits.是)
                        {
                            content.OutboundStateDesc = "已预配套,未配套";
                        }
                        else if (storeStockContents[i].OutboundState == OutboundStates.在库 && storeStockContents[i].IsSuit == IsSuits.否 && storeStockContents[i].IsPreSuit == IsSuits.否)
                        {
                            content.OutboundStateDesc = "库存";
                        }
                        contents.Add(content);
                    }
                    certificate.WhereAbouts = delivery.WhereAbouts;
                    certificate.OutNum = delivery.OutNum;
                    certificate.Remark = delivery.Remark;
                    certificate.operationPersonId = delivery.operationPersonId;
                    certificate.operationPerson = delivery.operationPerson;
                    certificate.operationTime = delivery.operationTime;
                    certificate.ScrapReason = delivery.ScrapReason;
                    certificate.ScrapReasonId = delivery.ScrapReasonId;
                    certificate.CertificateContents = contents;
                    certificate.CancellingTime = cancelling.CancellingTime;
                    certificate.CancellingUser = cancelling.CancellingUser;
                    certificate.CancellingUserId = cancelling.CancellingUserId;
                }
                return certificate;
            }
            else
            {
                throw new UserFriendlyException("无法查找该单据信息!");
            }
        }
        #endregion

        #region 报废
        /// <summary>
        /// 报废出库
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage ScrapStoreOut(ScrapInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                if (input.StoreList.Count == 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "请选择出库物料！";
                    return resultMessage;
                }
                List<StoreStockContent> stockContents = new List<StoreStockContent>();
                foreach (var item in input.StoreList)
                {
                    var ownContent = _storeStockContentRepsitory.Get(item);
                    if (ownContent.OutboundState == OutboundStates.出库)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "已出库,请先退库后在出库！";
                        return resultMessage;
                    }
                    if (ownContent.OutboundState == OutboundStates.未领料)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "正在出库待领料,请先撤销后在出库！";
                        return resultMessage;
                    }
                    if (ownContent.IsSuit == IsSuits.是)
                    {
                        if (input.IsRelieve == false)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = ownContent.ProductNumber + "已配套,请先解除配套后在出库！";
                            return resultMessage;
                        }
                    }
                    if (ownContent.IsPreSuit == IsSuits.是)
                    {
                        if (input.IsRelieve == false)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = ownContent.ProductNumber + "已预配套,请先解除预配套后在出库！";
                            return resultMessage;
                        }
                    }
                    stockContents.Add(ownContent);
                }
                var taskQuery = from tempTask in _makeTaskRepository.GetAll() select new { Model = tempTask.Model, LotNo = tempTask.LotNo, JobNumber = tempTask.JobNumber };
                DeliveryDocument delivery = new DeliveryDocument();
                var deliveryNo = _codeFormatDescAppServiceRepository.GetCodeFormat("出库管理");
                if (deliveryNo == null)
                {
                    delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                }
                else
                {
                    delivery.DeliveryNo = deliveryNo;
                }
                //delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                var tempOwnStock = stockContents[0];
                delivery.StoreId = tempOwnStock.StoreId;
                delivery.StroeName = tempOwnStock.StroeName;
                var ownTask = taskQuery.Where(d => d.Model == tempOwnStock.ProductCode && d.LotNo == tempOwnStock.SendTime).FirstOrDefault();
                if (ownTask != null)
                {
                    delivery.AssemblyTaskNumber = ownTask.JobNumber;
                }
                else
                {
                    delivery.AssemblyTaskNumber = "";
                }
                //delivery.ProductCode = tempOwnStock.ProductCode;
                //delivery.SendTime = tempOwnStock.SendTime;
                delivery.RetrievalState = OutboundRetrieval.报废;
                delivery.OutPeopleId = GetCurrentUser().Id;
                delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                delivery.OutNum = input.OutNum;
                delivery.Remark = input.Reason;
                delivery.operationPersonId = input.operationPersonId;
                delivery.operationPerson = input.operationPerson;
                delivery.operationTime = input.operationTime;
                delivery.ScrapReason = input.ScrapReason;
                delivery.ScrapReasonId = input.ScrapReasonId;
                delivery.ReleaseOrder = input.ReleaseOrder;
                delivery.QualifiedNumber = input.QualifiedNumber;
                delivery.StorePutTime = DateTime.Now;
                var guid = _deliveryDocumentRepository.InsertAndGetId(delivery);
                string deliveryStr = "";
                foreach (var item in stockContents)
                {
                    if (item.IsPreSuit == IsSuits.是)
                    {
                        item.IsPreSuit = IsSuits.否;
                        item.BomAnalysecontentId = null;
                    }
                    if (item.IsSuit == IsSuits.是)
                    {
                        item.IsSuit = IsSuits.否;
                        item.BomSuitContentId = null;
                    }
                    item.OutboundState = OutboundStates.未领料;
                    item.MaterialsProperty = MaterialsPropertys.报废品;
                    item.RetrievalState = OutboundRetrieval.报废;
                    _storeStockContentRepsitory.Update(item);
                    DeliveryOutRecord record = new DeliveryOutRecord();
                    record.DeliveryDocumentId = guid;
                    record.StoreStockContentId = item.Id;
                    record.ProductNumber = item.ProductNumber;
                    record.ReleaseOrder = item.ReleaseOrder;
                    record.QualifiedNumber = item.QualifiedNumber;
                    _deliveryOutRecordRepository.Insert(record);
                    deliveryStr = deliveryStr + item.ProductNumber + ",";
                }
                _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.出库管理, OperationTypes.报废出库, "报废出库:" + deliveryStr + "等物料信息。");
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        #endregion

        #region 返修品
        public ResultMessage RepairStoreOut(RepairInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                if (input.StoreList.Count == 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "请选择出库物料！";
                    return resultMessage;
                }
                List<StoreStockContent> stockContents = new List<StoreStockContent>();
                foreach (var item in input.StoreList)
                {
                    var ownContent = _storeStockContentRepsitory.Get(item);
                    if (ownContent.OutboundState == OutboundStates.出库)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "已出库,请先退库后在出库！";
                        return resultMessage;
                    }
                    if (ownContent.OutboundState == OutboundStates.未领料)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = ownContent.ProductNumber + "正在出库待领料,请先撤销后在出库！";
                        return resultMessage;
                    }
                    if (ownContent.IsSuit == IsSuits.是)
                    {
                        if (input.IsRelieve == false)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = ownContent.ProductNumber + "已配套,请先解除配套后在出库！";
                            return resultMessage;
                        }
                    }
                    if (ownContent.IsPreSuit == IsSuits.是)
                    {
                        if (input.IsRelieve == false)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = ownContent.ProductNumber + "已预配套,请先解除预配套后在出库！";
                            return resultMessage;
                        }
                    }
                    stockContents.Add(ownContent);
                }
                var taskQuery = from tempTask in _makeTaskRepository.GetAll() select new { Model = tempTask.Model, LotNo = tempTask.LotNo, JobNumber = tempTask.JobNumber };
                DeliveryDocument delivery = new DeliveryDocument();
                var deliveryNo = _codeFormatDescAppServiceRepository.GetCodeFormat("出库管理");
                if (deliveryNo == null)
                {
                    delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                }
                else
                {
                    delivery.DeliveryNo = deliveryNo;
                }
                //delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                var tempOwnStock = stockContents[0];
                delivery.StoreId = tempOwnStock.StoreId;
                delivery.StroeName = tempOwnStock.StroeName;
                var ownTask = taskQuery.Where(d => d.Model == tempOwnStock.ProductCode && d.LotNo == tempOwnStock.SendTime).FirstOrDefault();
                if (ownTask != null)
                {
                    delivery.AssemblyTaskNumber = ownTask.JobNumber;
                }
                else
                {
                    delivery.AssemblyTaskNumber = "";
                }
                //delivery.ProductCode = tempOwnStock.ProductCode;
                //delivery.SendTime = tempOwnStock.SendTime;
                delivery.RetrievalState = OutboundRetrieval.返修;
                delivery.OutPeopleId = GetCurrentUser().Id;
                delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                delivery.OutNum = input.OutNum;
                delivery.Remark = input.Remark;
                delivery.operationPersonId = input.operationPersonId;
                delivery.operationPerson = input.operationPerson;
                delivery.operationTime = input.operationTime;
                delivery.QualifiedNumber = input.QualifiedNumber;
                delivery.StorePutTime = DateTime.Now;
                var guid = _deliveryDocumentRepository.InsertAndGetId(delivery);
                string deliveryStr = "";
                foreach (var item in stockContents)
                {
                    item.OutboundState = OutboundStates.未领料;
                    item.MaterialsProperty = MaterialsPropertys.返修品;
                    item.RetrievalState = OutboundRetrieval.返修;
                    _storeStockContentRepsitory.Update(item);
                    DeliveryOutRecord record = new DeliveryOutRecord();
                    record.DeliveryDocumentId = guid;
                    record.StoreStockContentId = item.Id;
                    record.ProductNumber = item.ProductNumber;
                    record.ReleaseOrder = item.ReleaseOrder;
                    record.QualifiedNumber = item.QualifiedNumber;
                    _deliveryOutRecordRepository.Insert(record);
                    deliveryStr = deliveryStr + item.ProductNumber + ",";
                }
                _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.出库管理, OperationTypes.返修出库, "返修出库:" + deliveryStr + "等物料信息。");
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        #endregion

        #region 驳回出库
        public ResultMessage RejectDelivery(RejectInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var certificaQuery = _storePutContentRepsitory.GetAll().WhereIf(!string.IsNullOrEmpty(input.ReleaseOrder), item => item.ReleaseOrder == input.ReleaseOrder)
                      .WhereIf(!string.IsNullOrEmpty(input.QualifiedNumber), item => item.QualifiedNumber == input.QualifiedNumber).ToList();
                if (certificaQuery.Count > 0)
                {
                    var storeGuidList = certificaQuery.Select(d => d.Id).ToList();
                    var tempContent = from cc in _storeStockContentRepsitory.GetAll()
                                      join mm in storeGuidList on cc.StorePutContentId.Value equals mm
                                      select cc;

                    // .Where(d => storeGuidList.Contains(d.StorePutContentId.Value));
                    if (tempContent.Count() > 0)
                    {
                        List<StoreStockContent> stockContents = new List<StoreStockContent>();
                        foreach (var ownContent in tempContent)
                        {
                            if (ownContent.OutboundState == OutboundStates.出库)
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = ownContent.ProductNumber + "已出库,请先退库后在出库！";
                                return resultMessage;
                            }
                            if (ownContent.OutboundState == OutboundStates.未领料)
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = ownContent.ProductNumber + "正在出库待领料,请先撤销后在出库！";
                                return resultMessage;
                            }
                            if (ownContent.IsSuit == IsSuits.是)
                            {
                                if (input.IsRelieve == false)
                                {
                                    resultMessage.code = 1;
                                    resultMessage.Message = ownContent.ProductNumber + "已配套,请先解除配套后在出库！";
                                    return resultMessage;
                                }
                            }
                            if (ownContent.IsPreSuit == IsSuits.是)
                            {
                                if (input.IsRelieve == false)
                                {
                                    resultMessage.code = 1;
                                    resultMessage.Message = ownContent.ProductNumber + "已预配套,请先解除预配套后在出库！";
                                    return resultMessage;
                                }
                            }
                            stockContents.Add(ownContent);
                        }
                        var taskQuery = from tempTask in _makeTaskRepository.GetAll() select new { Model = tempTask.Model, LotNo = tempTask.LotNo, JobNumber = tempTask.JobNumber };
                        DeliveryDocument delivery = new DeliveryDocument();
                        var deliveryNo = _codeFormatDescAppServiceRepository.GetCodeFormat("出库管理");
                        if (deliveryNo == null)
                        {
                            delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                        }
                        else
                        {
                            delivery.DeliveryNo = deliveryNo;
                        }
                        //delivery.DeliveryNo = _codeFormatDescAppServiceRepository.GetOrderCode("CK", "yyyyMMdd", 1, 5, 1);
                        var tempOwnStock = stockContents[0];
                        delivery.StoreId = tempOwnStock.StoreId;
                        delivery.StroeName = tempOwnStock.StroeName;
                        var ownTask = taskQuery.Where(d => d.Model == tempOwnStock.ProductCode && d.LotNo == tempOwnStock.SendTime).FirstOrDefault();
                        if (ownTask != null)
                        {
                            delivery.AssemblyTaskNumber = ownTask.JobNumber;
                        }
                        else
                        {
                            delivery.AssemblyTaskNumber = "";
                        }
                        //delivery.ProductCode = tempOwnStock.ProductCode;
                        //delivery.SendTime = tempOwnStock.SendTime;
                        delivery.RetrievalState = OutboundRetrieval.驳回;
                        delivery.OutPeopleId = GetCurrentUser().Id;
                        delivery.OutPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                        delivery.OutNum = tempContent.Count();
                        delivery.Remark = input.Remark;
                        delivery.operationPersonId = input.operationPersonId;
                        delivery.operationPerson = input.operationPerson;
                        delivery.operationTime = input.operationTime;
                        delivery.QualifiedNumber = input.QualifiedNumber;
                        delivery.StorePutTime = DateTime.Now;
                        delivery.ReleaseOrder = input.ReleaseOrder;
                        var guid = _deliveryDocumentRepository.InsertAndGetId(delivery);
                        string deliveryStr = "";
                        foreach (var item in stockContents)
                        {
                            item.OutboundState = OutboundStates.未领料;
                            item.RetrievalState = OutboundRetrieval.驳回;
                            _storeStockContentRepsitory.Update(item);
                            DeliveryOutRecord record = new DeliveryOutRecord();
                            record.DeliveryDocumentId = guid;
                            record.StoreStockContentId = item.Id;
                            record.ProductNumber = item.ProductNumber;
                            record.ReleaseOrder = item.ReleaseOrder;
                            record.QualifiedNumber = item.QualifiedNumber;
                            _deliveryOutRecordRepository.Insert(record);
                            deliveryStr = deliveryStr + item.ProductNumber + ",";
                        }
                        _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.出库管理, OperationTypes.驳回出库, "驳回出库:" + deliveryStr + "等物料信息。");
                    }
                    else
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "暂无符合条件的库存物料！";
                        return resultMessage;
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        #endregion

        /// <summary>
        /// 确认出库
        /// </summary>
        /// <param name="Id"></param>
        public async Task<ResultMessage> ConfirmDelivery(Guid Id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var delivery = await _deliveryDocumentRepository.GetAsync(Id);
                if (!string.IsNullOrEmpty(delivery.IdentifyingPeople))
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该单据已经确认！不可重复确认！";
                    return resultMessage;
                }

                delivery.IdentifyingPeople = GetCurrentUser().Surname + GetCurrentUser().Name;
                delivery.IdentifyingTime = DateTime.Now;
                delivery.IdentifyingPeopleId = GetCurrentUser().Id;
                await _deliveryDocumentRepository.UpdateAsync(delivery);
                _iOperationHistoryAppService.InsertOperationLogNew(Id, BusinessTypes.出库管理, OperationTypes.确认出库, GetCurrentUser().Surname + GetCurrentUser().Name + "确认出库");
                var dataTemp = await _deliveryOutRecordRepository.GetAllListAsync(d => d.DeliveryDocumentId == Id);
                var data = dataTemp.Select(d => d.StoreStockContentId);
                var db = from temp in _storeStockContentRepsitory.GetAll()
                         join ppt in data on temp.Id equals ppt
                         select temp;
                foreach (var item in db)
                {
                    item.OutboundState = OutboundStates.出库;
                    item.DeliveryDocumentId = delivery.Id;
                    await _storeStockContentRepsitory.UpdateAsync(item);
                }
                if (delivery.RetrievalState != OutboundRetrieval.配套)
                {
                    var pTemp = (from temp in _storeStockContentRepsitory.GetAll()
                                 join temp1 in data on temp.Id equals temp1
                                 where temp.IsPreSuit == IsSuits.是 && temp.IsSuit == IsSuits.否
                                 select temp).ToList();
                    var isTemp = (from temp in _storeStockContentRepsitory.GetAll()
                                  join temp1 in data on temp.Id equals temp1
                                  where temp.IsPreSuit == IsSuits.是 && temp.IsSuit == IsSuits.是
                                  select temp).ToList();
                    if (pTemp.Count > 0)
                    {
                        await _bomAnalyseAppServiceRepository.ExteriorCancelPreSuite(pTemp);
                    }
                    if (isTemp.Count > 0)
                    {
                        await _matingManagerAppServiceRepository.ExteriorRelieveMating(pTemp);
                        await _bomAnalyseAppServiceRepository.ExteriorCancelPreSuite(pTemp);
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }

        }

        #region 退库
        /// <summary>
        /// 配套出库 退库
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage CancellingHandle(CancellingInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var delivery = _deliveryDocumentRepository.Get(input.DeliveryDocumentId);
                CancellingStocksDocument cancelling = new CancellingStocksDocument();
                cancelling.DeliveryDocumentId = input.DeliveryDocumentId;
                var cancellingStocksNo = _codeFormatDescAppServiceRepository.GetCodeFormat("退库管理");
                if (cancellingStocksNo == null)
                {
                    cancelling.CancellingStocksNo = _codeFormatDescAppServiceRepository.GetOrderCode("TK", "yyyyMMdd", 1, 5, 1);
                }
                else 
                {
                    cancelling.CancellingStocksNo = cancellingStocksNo;
                }
                //cancelling.CancellingStocksNo = _codeFormatDescAppServiceRepository.GetOrderCode("TK", "yyyyMMdd", 1, 5, 1);
                cancelling.DeliveryNo = delivery.DeliveryNo;
                cancelling.Cancelling = CancellingType.配套退库;
                cancelling.StoreId = delivery.StoreId;
                cancelling.StroeName = delivery.StroeName;
                cancelling.AssemblyTaskNumber = delivery.AssemblyTaskNumber;
                cancelling.ReleaseOrder = delivery.ReleaseOrder;
                cancelling.QualifiedNumber = delivery.QualifiedNumber;
                cancelling.Model = delivery.ProductCode;
                cancelling.LotNo = delivery.SendTime;
                List<Guid> StoreIds = new List<Guid>();
                foreach (var item in input.Matchings)
                {
                    if (item.StoreIdList != null)
                    {
                        if (item.StoreIdList.Count > 0)
                        {
                            StoreIds.AddRange(item.StoreIdList);
                        }
                        else
                        {
                            var tempStockIds = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.DeliveryDocumentId && d.LoadDetailsId == item.LoadDetailsId && d.IsCancelling == false);
                            if (tempStockIds.Count() > 0)
                            {
                                StoreIds.AddRange(tempStockIds.Select(d => d.StoreStockContentId));
                            }
                        }
                    }
                    else
                    {
                        var tempStockIds = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.DeliveryDocumentId && d.LoadDetailsId == item.LoadDetailsId && d.IsCancelling == false);
                        if (tempStockIds.Count() > 0)
                        {
                            StoreIds.AddRange(tempStockIds.Select(d => d.StoreStockContentId));
                        }
                    }
                }
                if (StoreIds.Count == 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "请选择符合条件的配套物料，然后执行退库操作！";
                    return resultMessage;
                }
                cancelling.CancellingReason = input.CancellingReason;
                cancelling.CancellingUser = input.CancellingUser;
                cancelling.CancellingUserId = input.CancellingUserId;
                cancelling.CancellingTime = DateTime.Now;
                var guid = _cancellingStocksDocumentRepository.InsertAndGetId(cancelling);
                string cancellingStr = "";
                foreach (var item in StoreIds)
                {
                    var storeRecord = _deliveryOutRecordRepository.FirstOrDefault(d => d.StoreStockContentId == item && d.DeliveryDocumentId == input.DeliveryDocumentId);
                    if (storeRecord != null)
                    {
                        storeRecord.IsCancelling = true;
                        _deliveryOutRecordRepository.Update(storeRecord);
                        CancellingRecord cancellingRecord = new CancellingRecord();
                        cancellingRecord.CancellingStocksId = guid;
                        cancellingRecord.StoreStockContentId = item;
                        cancellingRecord.QualifiedNumber = storeRecord.QualifiedNumber;
                        cancellingRecord.ReleaseOrder = storeRecord.ReleaseOrder;
                        cancellingRecord.ProductNumber = storeRecord.ProductNumber;
                        _cancellingRecordRepository.Insert(cancellingRecord);
                        cancellingStr = cancellingStr + storeRecord.ProductNumber + ",";
                        var tempStore = _storeStockContentRepsitory.Get(item);
                        tempStore.OutboundState = OutboundStates.在库;
                        tempStore.DeliveryDocumentId = null;
                        _storeStockContentRepsitory.Update(tempStore);
                    }
                }
                _iOperationHistoryAppService.InsertOperationLogNew(delivery.Id, BusinessTypes.出库管理, OperationTypes.退库, "退库物料编号为:" + cancellingStr);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 新增出库 退库
        /// </summary>
        public ResultMessage AddCancellingHandle(OthersCancellingInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try { 
            if (input.StoreIdList.Count == 0)
            {
                resultMessage.code = 1;
                resultMessage.Message = "请选择符合条件的配套物料，然后执行退库操作！";
                return resultMessage;
            }
            var delivery = _deliveryDocumentRepository.Get(input.DeliveryDocumentId);
            CancellingStocksDocument cancelling = new CancellingStocksDocument();
            var cancellingStocksNo = _codeFormatDescAppServiceRepository.GetCodeFormat("退库管理");
            if (cancellingStocksNo == null)
            {
                cancelling.CancellingStocksNo = _codeFormatDescAppServiceRepository.GetOrderCode("TK", "yyyyMMdd", 1, 5, 1);
            }
            else
            {
                cancelling.CancellingStocksNo = cancellingStocksNo;
            }
            //cancelling.CancellingStocksNo = _codeFormatDescAppServiceRepository.GetOrderCode("TK", "yyyyMMdd", 1, 5, 1);
            cancelling.DeliveryDocumentId = input.DeliveryDocumentId;
            cancelling.DeliveryNo = delivery.DeliveryNo;
            cancelling.Cancelling = CancellingType.新增退库;
            cancelling.StoreId = delivery.StoreId;
            cancelling.StroeName = delivery.StroeName;
            cancelling.AssemblyTaskNumber = delivery.AssemblyTaskNumber;
            cancelling.ReleaseOrder = delivery.ReleaseOrder;
            cancelling.QualifiedNumber = delivery.QualifiedNumber;
            cancelling.Model = delivery.ProductCode;
            cancelling.LotNo = delivery.SendTime;
            cancelling.CancellingReason = input.CancellingReason;
            cancelling.CancellingUser = input.CancellingUser;
            cancelling.CancellingUserId = input.CancellingUserId;
            cancelling.CancellingTime = DateTime.Now;
            var guid = _cancellingStocksDocumentRepository.InsertAndGetId(cancelling);
            var stockList = _deliveryOutRecordRepository.GetAll().Where(d => d.DeliveryDocumentId == input.DeliveryDocumentId && input.StoreIdList.Contains(d.StoreStockContentId));
            string cancellingStr = "";
            foreach (var item in stockList)
            {
                if (item.IsCancelling == true)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = item.ProductNumber + "已在其他单据退库!";
                    return resultMessage;
                }
                item.IsCancelling = true;
                _deliveryOutRecordRepository.Update(item);
                CancellingRecord cancellingRecord = new CancellingRecord();
                cancellingRecord.CancellingStocksId = guid;
                cancellingRecord.StoreStockContentId = item.StoreStockContentId;
                cancellingRecord.QualifiedNumber = item.QualifiedNumber;
                cancellingRecord.ReleaseOrder = item.ReleaseOrder;
                cancellingRecord.ProductNumber = item.ProductNumber;
                _cancellingRecordRepository.Insert(cancellingRecord);
                cancellingStr = cancellingStr + item.ProductNumber + ",";
                var tempStore = _storeStockContentRepsitory.Get(item.StoreStockContentId);
                tempStore.OutboundState = OutboundStates.在库;
                tempStore.DeliveryDocumentId = null;
                _storeStockContentRepsitory.Update(tempStore);
            }
            _iOperationHistoryAppService.InsertOperationLogNew(delivery.Id, BusinessTypes.出库管理, OperationTypes.退库, "退库物料编号为:" + cancellingStr);
            resultMessage.code = 0;
            return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        #endregion

        #region 盘点
        /// <summary>
        /// 创建盘点单据
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage CreateInventoryStore(InventoryInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                InventoryStore inventory = new InventoryStore();
                inventory.InventoryEndTime = input.InventoryEndTime;
                inventory.InventoryStartTime = input.InventoryStartTime;
                inventory.InventoryNo = input.InventoryNo;
                inventory.InventoryPeopleId = GetCurrentUser().Id;
                inventory.MaterialsNodeId = input.MaterialsNodeId;
                inventory.InventoryState = InventoryState.已创建;
                inventory.StoreId = input.StoreId;
                inventory.StroeName = input.StroeName;
                var guid = _inventoryStoreRecordRepository.InsertAndGetId(inventory);
                _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.盘点库存, OperationTypes.创建盘点单据, GetCurrentUser().Surname + GetCurrentUser().Name + "创建盘点单据");
                var users = from tempUser in _userRepository.GetAll() select new { Id = tempUser.Id, UserName = tempUser.Surname + tempUser.Name };
                var query = from temp in _storePutContentRepsitory.GetAll()
                            orderby temp.CreationTime descending
                            join tempMaterial in _materialsContentrepository.GetAll() on temp.MaterialsContentId equals tempMaterial.Id
                            join tempNode in _materialsNoderepository.GetAll() on tempMaterial.MaterialsNodeId equals tempNode.Id
                            join tempMaterialCategory in _materialsNoderepository.GetAll() on tempMaterial.MaterialCategoryId equals tempMaterialCategory.Id
                            where tempMaterial.MaterialsNodeId == input.MaterialsNodeId
                            select new InventoryDetails
                            {
                                StorePutId = temp.Id,
                                InventoryId = guid,
                                StroeName = temp.StroeName,
                                BinLocation = temp.BinLocation,
                                ProductDrawingNo = temp.ProductDrawingNo,
                                ProductName = temp.ProductName,
                                Module = temp.Module,
                                MaterialsNodeDesc = tempNode.MaterialTypeName,
                                MaterialsContentDsec = tempMaterialCategory.MaterialTypeName,
                                MaterialsContentId = tempMaterialCategory.Id,
                                MaterialsNodeId = tempNode.Id,
                                MaterialsPropertyDesc = GetEnumDesc(temp.MaterialsProperty),
                                MaterialsProperty = temp.MaterialsProperty,
                                QualifiedNumber = temp.QualifiedNumber,
                                ReleaseOrder = temp.ReleaseOrder,
                            };
                foreach (var item in query)
                {
                    var tempData = _storeStockContentRepsitory.GetAll().Where(d => d.StorePutContentId == item.StorePutId).Where(d => d.OutboundState == OutboundStates.在库).ToList();
                    if (tempData.Count > 0)
                    {
                        item.StoreQuantity = tempData.Count;
                        item.StoreProductNumber = string.Join(",", tempData.Select(d => d.ProductNumber));
                        item.InventoryNo = item.StoreQuantity;
                        item.InventoryPartNo = item.StoreProductNumber;
                        _inventoryDetailsRepository.Insert(item);
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 根据查询条件盘点单据信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<InventoryOutput> GetInventorys(InventorySelectInput input)
        {
            List<InventoryOutput> inventories = new List<InventoryOutput>();
            int count = 0;
            var tempQuery = _inventoryStoreRecordRepository.GetAll().WhereIf(!string.IsNullOrEmpty(input.InventoryNo), item => item.InventoryNo.Contains(input.InventoryNo))
                   .WhereIf(input.StoreId != null, item => item.StoreId == input.StoreId)
                   .WhereIf(input.InventoryStartTime != null, item => item.InventoryStartTime >= input.InventoryStartTime)
                   .WhereIf(input.InventoryEndTime != null, item => item.InventoryEndTime >= input.InventoryEndTime)
                   .WhereIf(input.InventoryState != null, item => item.InventoryState == input.InventoryState)
                   .WhereIf(input.MaterialsNodeId != null, item => item.MaterialsNodeId == input.MaterialsNodeId)
                   .WhereIf(input.InventoryPeopleId != null, item => item.InventoryPeopleId == input.InventoryPeopleId);
            if (tempQuery.Count() > 0)
            {
                var users = (from tempUser in _userRepository.GetAll() select new { Id = tempUser.Id, UserName = tempUser.Surname + tempUser.Name }).ToList();
                inventories = (from temp in tempQuery
                               orderby temp.CreationTime descending
                               join tempUser in users on temp.InventoryPeopleId equals tempUser.Id
                               join tempMaterialsNode in _materialsNoderepository.GetAll() on temp.MaterialsNodeId equals tempMaterialsNode.Id
                               select new InventoryOutput
                               {
                                   Id = temp.Id,
                                   InventoryNo = temp.InventoryNo,
                                   StroeName = temp.StroeName,
                                   MaterialsNodeDesc = tempMaterialsNode.MaterialTypeName,
                                   InventoryStartTime = temp.InventoryStartTime,
                                   InventoryEndTime = temp.InventoryEndTime,
                                   InventoryStateDesc = GetEnumDesc(temp.InventoryState),
                                   InventoryPeopleDesc = tempUser.UserName,
                                   InventoryRstartTime =temp.InventoryRstartTime,
                                   InventoryREndTime=temp.InventoryREndTime
                               }).ToList();
                count = tempQuery.Count();
                inventories = inventories.AsQueryable().PageBy(input).ToList();
            }
            return new PagedResultDto<InventoryOutput>(count, inventories);
        }
        /// <summary>
        /// 生成流水号
        /// </summary>
        /// <returns></returns>
        public string GetInventoryNo()
        {
            int count = _inventoryStoreRecordRepository.Count();
            if (count == 0)
            {
                return DateTime.Now.ToString("yyyyMM01");
            }
            else
            {
                string inVentory = _inventoryStoreRecordRepository.GetAll().Select(d => d.InventoryNo).Max();
                string newInVentory = (int.Parse(inVentory) + 1).ToString();
                return newInVentory;
            }
        }
        /// <summary>
        /// 结束盘点
        /// </summary>
        /// <param name="Id"></param>
        public ResultMessage FinishInventory(Guid Id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inventory = _inventoryStoreRecordRepository.Get(Id);
                inventory.InventoryState = InventoryState.已盘点;
                inventory.InventoryREndTime = DateTime.Now;
                _inventoryStoreRecordRepository.Update(inventory);
                _iOperationHistoryAppService.InsertOperationLogNew(Id, BusinessTypes.盘点库存, OperationTypes.结束盘点, GetCurrentUser().Surname + GetCurrentUser().Name + "于" + DateTime.Now.ToString() + "结束盘点");
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        /// <summary>
        /// 查看盘点单据信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<InventoryDetailsOutput> GetInventory(InventoryDetailsInput input)
        {
            var tempData = _inventoryDetailsRepository.GetAll().Where(d => d.InventoryId == input.InventoryId).WhereIf(!string.IsNullOrEmpty(input.ProductDrawingNo), d => d.ProductDrawingNo.Contains(input.ProductDrawingNo))
            .WhereIf(!string.IsNullOrEmpty(input.ProductName), d => d.ProductName.Contains(input.ProductName))
            .WhereIf(!string.IsNullOrEmpty(input.Module), d => d.Module.Contains(input.Module))
            .WhereIf(input.MaterialsContentId != null, d => d.MaterialsContentId == input.MaterialsContentId)
            .WhereIf(input.MaterialsNodeId != null, d => d.MaterialsNodeId == input.MaterialsNodeId)
            .WhereIf(input.MaterialsProperty != null, d => d.MaterialsProperty == input.MaterialsProperty)
            .WhereIf(input.QualifiedNumber != null, d => d.QualifiedNumber.Contains(input.QualifiedNumber))
            .WhereIf(input.ReleaseOrder != null, d => d.ReleaseOrder.Contains(input.ReleaseOrder));
            var result = from tempInventory in tempData
                         select new InventoryDetailsOutput
                         {
                             Id= tempInventory.Id,
                             StroeName = tempInventory.StroeName,
                             BinLocation = tempInventory.BinLocation,
                             ProductDrawingNo = tempInventory.ProductDrawingNo,
                             ProductName = tempInventory.ProductName,
                             Module = tempInventory.Module,
                             MaterialsNodeDesc = tempInventory.MaterialsNodeDesc,
                             MaterialsContentDsec = tempInventory.MaterialsContentDsec,
                             MaterialsPropertyDesc = tempInventory.MaterialsPropertyDesc,
                             QualifiedNumber = tempInventory.QualifiedNumber,
                             ReleaseOrder = tempInventory.ReleaseOrder,
                             StoreQuantity = tempInventory.StoreQuantity,
                             StoreProductNumber = tempInventory.StoreProductNumber,
                             InventoryNo = tempInventory.InventoryNo,
                             InventoryPartNo = tempInventory.InventoryPartNo,
                             Remark = tempInventory.Remark,
                             DifferenceCount = tempInventory.InventoryNo - tempInventory.StoreQuantity,
                         };
            return result.ToList();
        }
        /// <summary>
        /// 修改盘点记录
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage ReNewInventory(ReNewInventoryInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var doc = _inventoryStoreRecordRepository.Get(input.InventoryDocumentId);
                doc.InventoryRstartTime = DateTime.Now;
                _inventoryStoreRecordRepository.Update(doc);
                _iOperationHistoryAppService.InsertOperationLogNew(input.InventoryDocumentId, BusinessTypes.盘点库存, OperationTypes.结束盘点, GetCurrentUser().Surname + GetCurrentUser().Name + "于" + DateTime.Now.ToString() + "盘点库存信息");
                foreach (var item in input.Parts)
                {
                    var inventroy = _inventoryDetailsRepository.GetAll().Where(d => d.Id == item.Id).FirstOrDefault();
                    if (inventroy != null)
                    {
                        inventroy.InventoryNo = item.InventoryNo;
                        inventroy.InventoryPartNo = item.InventoryPartNo;
                        inventroy.Remark = item.Remark;
                        _inventoryDetailsRepository.Update(inventroy);
                    }
                    else
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "传入数据有误！未发现相关数据！";
                        return resultMessage;
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        #endregion

        #region 获取下拉列表
        public List<LabelCollection> GetStoreDropList()
        {
            List<LabelCollection> collections = new List<LabelCollection>();

            collections = (from store in _storeRepository.GetAll().Where(s => s.StoreUse == StoreEnum.StoreIsUse.是)
                           select new LabelCollection
                           {
                               Label = store.StroeName,
                               Value = store.Id
                           }).ToList();
            return collections;
        }
        /// <summary>
        /// 获取盘点人
        /// </summary>
        /// <returns></returns>
        public List<LabelCollectLong> GetInventoryPeopleList()
        {
            List<LabelCollectLong> collections = new List<LabelCollectLong>();

            var roleUser = _roleRepository.GetAll().Where(d => d.DisplayName.Contains("Mes57")).Select(d => d.Id);
            var userIdList = _userRoleRepository.GetAll().Where(d => roleUser.Contains(d.RoleId)).Select(d => d.UserId).Distinct();
            var users = _userRepository.GetAll().Where(d => userIdList.Contains(d.Id));
            collections = (from tempUser in users
                           select new LabelCollectLong
                           {
                               Value = tempUser.Id,
                               Label = tempUser.Surname + tempUser.Name
                           }).ToList();
            return collections;
        }
        /// <summary>
        /// 获取物料下拉详情
        /// </summary>
        /// <returns></returns>
        public List<LabelCollection> GetMaterialList()
        {
            List<LabelCollection> collections = new List<LabelCollection>();
            collections = (from tempMaterial in _materialsNoderepository.GetAll()
                           select new LabelCollection
                           {
                               Label = tempMaterial.MaterialTypeName,
                               Value = tempMaterial.Id
                           }).ToList();
            return collections;
        }
        /// <summary>
        /// 获取物料属性
        /// </summary>
        /// <returns></returns>
        public List<LabelCollectInt> GetMaterialsPropertysDesc()
        {
            List<LabelCollectInt> temp = new List<LabelCollectInt>();
            foreach (int myCode in Enum.GetValues(typeof(MaterialsPropertys)))
            {
                LabelCollectInt work = new LabelCollectInt();
                string strName = Enum.GetName(typeof(MaterialsPropertys), myCode);//获取名称
                work.Value = myCode;
                work.Label = strName;
                temp.Add(work);
            }
            return temp;
        }
        /// <summary>
        /// 获取盘点状态
        /// </summary>
        /// <returns></returns>
        public List<LabelCollectInt> GetInventoryStateDesc()
        {
            List<LabelCollectInt> temp = new List<LabelCollectInt>();
            foreach (int myCode in Enum.GetValues(typeof(InventoryState)))
            {
                LabelCollectInt work = new LabelCollectInt();
                string strName = Enum.GetName(typeof(InventoryState), myCode);//获取名称
                work.Value = myCode;
                work.Label = strName;
                temp.Add(work);
            }
            return temp;
        }
        /// <summary>
        /// 获取出库单据类型
        /// </summary>
        /// <returns></returns>
        public List<LabelCollectInt> GetOutboundRetrievalDesc()
        {
            List<LabelCollectInt> temp = new List<LabelCollectInt>();
            foreach (int myCode in Enum.GetValues(typeof(OutboundRetrieval)))
            {
                LabelCollectInt work = new LabelCollectInt();
                string strName = Enum.GetName(typeof(OutboundRetrieval), myCode);//获取名称
                work.Value = myCode;
                work.Label = strName;
                temp.Add(work);
            }
            return temp;
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 根据枚举获取枚举描述信息
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static string GetEnumDesc(System.Enum parm)
        {
            FieldInfo enumInfo = parm.GetType().GetField(parm.ToString());
            if (enumInfo == null)
            {
                return "";
            }
            DescriptionAttribute[] enumAttributes
                = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (enumAttributes.Length > 0)
            {
                return enumAttributes[0].Description;
            }
            return parm.ToString();
        }
        /// <summary>
        /// 查找当前节点类型 1 任务-节点  2 节点-节点 3 节点-工序 4 工序-工步 5 工步
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        private int RouteType(Guid ParentId)
        {
            var bopDesc = _bopDescRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (bopDesc != null)
            {
                return 1;
            }
            var bopNode = _bopNodeRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (bopNode != null)
            {
                if (!string.IsNullOrEmpty(bopNode.ProcessCode))
                {
                    return 3;
                }
                else
                {
                    return 2;
                }
            }
            var processEntity = _processesEntityRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (processEntity != null)
            {
                return 4;
            }
            var workEntity = _workStepEntityRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (workEntity != null)
            {
                return 5;
            }
            return 0;
        }

        /// <summary>
        /// 获取配套状态
        /// </summary>
        /// <param name="processDosage">工艺用量</param>
        /// <param name="suiteStock">配套数量</param>
        /// <param name="preSuiteStock">预配套数量</param>
        /// <param name="available">可用预配套数量</param>
        /// <returns></returns>
        private string GetAssortStateDesc(int processDosage, int suiteStock, int preSuiteStock,int available)
        {

            if (preSuiteStock == 0)
            {
                return "未预配套";
            }
            // 缺料：
            if (processDosage - suiteStock > available)
            {
                return "缺料";
            }
            else
            {
                if (processDosage - suiteStock == 0)
                {
                    return "已配套";
                }
                if (suiteStock == 0)
                {
                    return "未配套";
                }
                return "配套中";
            }
        }
        #endregion



    }
}
